问题
I have a macro in Outlook VBA to grab data from an open Excel workbook ("Workbook1").
I reference the workbook as follows:
Dim objApp As Excel.Application
Set objApp = GetObject(, "Excel.Application")
Set wb = objApp.Workbooks("Workbook1.xlsx")
I often get runtime error 9, that VBA cannot find the workbook.
I think since I have more than one Excel instance open, VBA is looking for my workbook in the wrong instance.
How do I reference my workbook when running more than one Excel instance?
回答1:
Try This
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
Or This which works for me.
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
回答2:
I suspect that changing the file name to add in the full file path would work, so try changing the line:
Set wb = objApp.Workbooks("Workbook1.xlsx")
To something like:
Set wb = objApp.Workbooks("C:\Users\Documents\Workbook1.xlsx")
回答3:
If you want to set the objApp
to a particular instance of Excel,
you can do so using the name of an open workbook in that instance:
Dim objApp As Excel.Application
Dim objWbk As Excel.Workbook
Dim wB As Excel.Workbook
Set objWbk = GetObject("Workbook1.xlsx")
Set objApp = objWb.Application
Set wB = objApp.Workbooks("Workbook1.xlsx")
来源:https://stackoverflow.com/questions/41716693/finding-a-workbook-in-one-of-multiple-excel-instances