简体   繁体   English

关闭工作簿并在另一个工作簿中完成 VBA 程序

[英]Close workbook and finish VBA procedure in another workbook

I use the following VBA to create a copy of the spreadsheet which is used:我使用以下 VBA 创建所用电子表格的副本:

Sub Files()
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\testfile.xlsm"
Workbooks.Open "C:\Users\" & Environ("Username") & "\Desktop\" & "testfile.xlsm", UpdateLinks:=False
ThisWorkbook.Close SaveChanges = False
MsgBox ("File saved successfully on desktop.")
End Sub

This code puts a copy of the Excel file on the desktop.此代码将 Excel 文件的副本放在桌面上。 Once this is done the new created Excel file is opened and the other one is closed.完成此操作后,将打开新创建的 Excel 文件并关闭另一个文件。
However, the closing of the other one causes the VBA to stop as well;但是,另一个的关闭也会导致 VBA 停止; therefore, the MsgBox ("File saved successfully on desktop.") does not appear anymore.因此, MsgBox ("File saved successfully on desktop.")不再出现。

How do I have to change the VBA so it continues in the new opened spreadsheet and displays the message box?我如何更改 VBA 以便它在新打开的电子表格中继续并显示消息框?

ThisWorkbook.Close SaveChanges = False closes the workbook. ThisWorkbook.Close SaveChanges = False关闭工作簿。 The VBA code is inside, thus the MsgBox does not appear. VBA 代码在里面,因此MsgBox不会出现。

The easiest solution is to change a bit your code like this:最简单的解决方案是像这样更改代码:

MsgBox ("File saved successfully on desktop.")
ThisWorkbook.Close SaveChanges = False

To make sure that your MsgBox does not "lie", introduce Error-capture:为了确保您的 MsgBox 不会“撒谎”,请引入错误捕获:

Sub Files()

    On Error GoTo Files_Error

    ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\testfile.xlsm"
    Workbooks.Open "C:\Users\" & Environ("Username") & "\Desktop\" & "testfile.xlsm", UpdateLinks:=False
    MsgBox ("File saved successfully on desktop.")
    ThisWorkbook.Close SaveChanges = False

    On Error GoTo 0
    Exit Sub

Files_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Files of Sub Modul1"

End Sub

If the file cannot be saved after the MsgBox , a new MsgBox would pop-up.如果在MsgBox之后无法保存文件,则会弹出一个新的MsgBox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM