GetObject 有效,CreateObject 无效

GetObject works, CreateObject doesn't

尝试编写一个脚本

第一个选项效果很好!第二个选项不起作用,也没有给出任何解释,只是退出,什么都不做!

Dim objXLApp, objXLWb, objXLWs
Dim XLWasRunning

XLWasRunning = True

Set objXLApp = GetObject(, "Excel.Application")

If Not TypeName(objXLApp) = "Empty" Then
    strMessage = "Excel Running."
Else
    strMessage = "Excel Not Running."
    Set objXLApp = CreateObject("Excel.Application")
End If

Set objXLWb = objXLApp.Workbooks.Open("F:\GFD\Sam\Test\test.xlsx")
Set objXLWs = objXLWb.Sheets(1)

编辑:将 CreateObject(, "Excel.Application") 更改为 CreateObject("Excel.Application")

根据您收到的评论,此代码应该有效:

Dim objXLApp, objXLWb, objXLWs
Dim XLWasRunning
Dim strMessage

' Get running instance
Set objXLApp = GetObject("", "Excel.Application")

If Not objXLApp Is Nothing Then
    strMessage = "Excel Running."
    XLWasRunning = True
Else
    strMessage = "Excel Not Running."
    Set objXLApp = CreateObject("Excel.Application")
    XLWasRunning = False
End If

objXLApp.Visible = True

Set objXLWb = objXLApp.Workbooks.Open("C:\Temp\test.xlsx")
Set objXLWs = objXLWb.Sheets(1)

您可能想要添加以下内容以检查是否应再次加载工作簿:

If Not XLWasRunning Then
    Set objXLWb = objXLApp.Workbooks.Open("C:\Temp\test.xlsx")
    Set objXLWs = objXLWb.Sheets(1)
End If

如果 Excel 已经 运行 您还可以在加载之前检查您的工作簿是否已经加载:

Dim bWorkbookFound
bWorkbookFound = False
For Each objXLWb In objXLApp.Workbooks
    If objXLWb.Name = "test.xlsx" Then
        ' Workbook already loaded
        bWorkbookFound = True
        objXLWb.Activate
    End If
Next