Finding a workbook in one of multiple Excel instances

后端 未结 3 1197
清歌不尽
清歌不尽 2020-12-06 23:48

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


        
相关标签:
3条回答
  • 2020-12-06 23:56

    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")
    
    0 讨论(0)
  • 2020-12-07 00:11

    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
    
    0 讨论(0)
  • 2020-12-07 00:20

    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")
    
    0 讨论(0)
提交回复
热议问题