VBScript代码可保持Excel文件打开 [英] VBScript code to keep Excel file open

查看:67
本文介绍了VBScript代码可保持Excel文件打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个VBScript代码来打开excel文件,运行宏并关闭它.美好的.

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.

如果我删除了两行代码xlApp.activewindow.close和xlApp.Quit,则无论如何该工作簿和该应用程序都是关闭的,但它们仍在后台打开(Excel进程在任务管理器中仍处于活动状态).因此,以后无法通过再次调用脚本在同一文件上重新运行宏(这正是我要执行的操作).

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).

为什么?

这是代码:

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

推荐答案

您只需要使新的Excel实例可见即可.创建后立即执行此操作:

You just need to make your new instance of Excel visible. Do this right after creating it:

xlApp.Visible = True

这篇关于VBScript代码可保持Excel文件打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆