简体   繁体   中英

VBScript code to keep Excel file open

I have a VBScript code to open an excel file, run a macro and close it. 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). 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. 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 );

xlApp.activewindow.close

This line will quit Excel application;

xlApp.Quit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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