我在 Outlook VBA 中有一个宏来从打开的 Excel 工作簿(“Workbook1”)中获取数据。
我引用工作簿如下:
Dim objApp As Excel.Application
Set objApp = GetObject(, "Excel.Application")
Set wb = objApp.Workbooks("Workbook1.xlsx")
我经常收到运行时错误 9 ,即 VBA 找不到工作簿。
我想因为我打开了多个 Excel 实例, VBA 正在错误的实例中查找我的工作簿 .
我如何 运行多个 Excel 实例时引用我的工作簿 ?
最佳答案
尝试这个
Option Explicit
Public Sub Example()
Dim xlApp As Excel.Application
Dim Book As Workbook
Set xlApp = New Excel.Application
Set Book = xlApp.Workbooks.Open(Environ( _
"USERPROFILE") & "\Documents\Temp\Temp.xlsm")
' Do something
Set xlApp = Nothing
Set Book = Nothing
End Sub
或者这对我有用。
Option Explicit
Public Sub Example()
Dim xlApp As Excel.Application
Dim Book As Excel.Workbook
Dim Sht As Excel.Worksheet
Dim xlStarted As Boolean
Dim FilePath As String
Dim Cell As Range
Dim Rng As Range
' // File Path
FilePath = "C:\Temp\Temp.xlsx"
Debug.Print FilePath
' // If Error get Excel Application
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
xlStarted = True
End If
On Error GoTo 0
' // Open Workbook, Sheet1 to get data
Set Book = xlApp.Workbooks.Open(FilePath)
Set Sht = Book.Sheets("Sheet1")
' // Set range variable
Set Rng = Sht.Range("A1")
For Each Cell In Rng
Debug.Print Cell.Value
Next
'// Close & SaveChanges
Book.Close SaveChanges:=True
If xlStarted Then
xlApp.Quit
End If
Set xlApp = Nothing
Set Book = Nothing
Set Sht = Nothing
End Sub
关于excel - 在多个 Excel 实例之一中查找工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716693/