在多个Excel实例之一中查找工作簿

时间:2017-01-18 10:18:23

标签: excel vba outlook outlook-vba

我在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实例时引用我的工作簿

3 个答案:

答案 0 :(得分:3)

试试这个

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

答案 1 :(得分:1)

我怀疑更改文件名以在完整文件路径中添加会有效,因此请尝试更改该行:

Set wb = objApp.Workbooks("Workbook1.xlsx")

类似于:

Set wb = objApp.Workbooks("C:\Users\Documents\Workbook1.xlsx")

答案 2 :(得分:1)

如果要将objApp设置为特定的Excel实例,

您可以使用该实例中的打开工作簿的名称来执行此操作:

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