[英]VBScript code to keep Excel file open
I have a VBScript code to open an excel file, run a macro and close it. 我有一个VBScript代码来打开excel文件,运行宏并关闭它。 Fine.
精细。
Now, the only thing I want to change is to leave the file open. 现在,我唯一要更改的就是将文件保持打开状态。
If I remove the 2 lines of code xlApp.activewindow.close and xlApp.Quit, then the workbook and the application are closed anyway, but they remain open in the background (Excel process still active in Task Manager). 如果我删除了两行代码xlApp.activewindow.close和xlApp.Quit,则无论如何该工作簿和该应用程序都是关闭的,但它们仍在后台打开(Excel进程在任务管理器中仍处于活动状态)。 Hence, it is impossible to re-run the macro later on the same file by calling the script again (which is exactly what I want to do).
因此,以后无法通过再次调用脚本在同一文件上重新运行宏(这正是我要执行的操作)。
Why? 为什么?
Here is the code: 这是代码:
Option Explicit
On Error Resume Next
MyTest
Sub MyTest()
Dim xlApp
Dim xlBook
Dim fpath
Dim fname
' Excel application running? if not, open Excel
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If xlApp <> "Microsoft Excel" Then
Set xlApp = CreateObject("Excel.Application")
End If
Err.Clear
' correct Excel file open? if not, open it
fpath = "D:\Desktop\"
fname = "MyTest.xls"
xlApp.Workbooks(fname).Activate
If Err = 0 Then
' no error, so it has been possible to activate the workbook
Set xlBook = xlApp.Workbooks(fname)
Else
' unable to activate, so workbook was not open -> open it now
Set xlBook = xlApp.Workbooks.Open(fpath & fname, 0, True)
End If
Err.Clear
' now run the desired macro in the excel file
xlApp.Run "HelloWorld"
' WANT TO CHANGE THIS
xlBook.saved = True
xlApp.activewindow.close
' AND THIS
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
You just need to make your new instance of Excel visible. 您只需要使新的Excel实例可见即可。 Do this right after creating it:
创建后立即执行以下操作:
xlApp.Visible = True
This line of code will close your current activated workbook (by now, it is D:\\Destop\\MyTest.xls
); 这行代码将关闭您当前激活的工作簿(到目前为止,它是
D:\\Destop\\MyTest.xls
);
xlApp.activewindow.close
This line will quit Excel application; 此行将退出Excel应用程序;
xlApp.Quit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.