代码之家  ›  专栏  ›  技术社区  ›  I. J. Kennedy ShankarSangoli

VBA能否跨Excel实例访问?

  •  29
  • I. J. Kennedy ShankarSangoli  · 技术社区  · 14 年前

    在一个Excel实例中运行的Excel VBA宏能否访问另一个正在运行的Excel实例的工作簿?例如,我想创建一个在任何运行的Excel实例中打开的所有工作簿的列表。

    7 回复  |  直到 14 年前
        1
  •  33
  •   ForEachLoop    14 年前

    科尼利厄斯的回答部分正确。他的代码获取当前实例,然后生成一个新实例。 获取对象

    对于VBA项目,创建两个模块,一个是代码模块,另一个是带有一个名为Command1的命令按钮的窗体。您可能需要添加对Microsoft.Excel的引用。

    此代码在即时窗口中显示每个正在运行的Excel实例的每个工作簿的所有名称。

    '------------- Code Module --------------
    
    Option Explicit
    
    Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
    Declare Function GetClassName Lib "User32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
    Declare Function IIDFromString Lib "ole32" (ByVal lpsz As Long, ByRef lpiid As UUID) As Long
    Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As UUID, ByRef ppvObject As Object) As Long
    
    Type UUID 'GUID
      Data1 As Long
      Data2 As Integer
      Data3 As Integer
      Data4(7) As Byte
    End Type
    
    '------------- Form Module --------------
    
    Option Explicit
    
    Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
    Const OBJID_NATIVEOM As Long = &HFFFFFFF0
    
    'Sub GetAllWorkbookWindowNames()
    Sub Command1_Click()
        On Error GoTo MyErrorHandler
    
        Dim hWndMain As Long
        hWndMain = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    
        Do While hWndMain <> 0
            GetWbkWindows hWndMain
            hWndMain = FindWindowEx(0&, hWndMain, "XLMAIN", vbNullString)
        Loop
    
        Exit Sub
    
    MyErrorHandler:
        MsgBox "GetAllWorkbookWindowNames" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Sub
    
    Private Sub GetWbkWindows(ByVal hWndMain As Long)
        On Error GoTo MyErrorHandler
    
        Dim hWndDesk As Long
        hWndDesk = FindWindowEx(hWndMain, 0&, "XLDESK", vbNullString)
    
        If hWndDesk <> 0 Then
            Dim hWnd As Long
            hWnd = FindWindowEx(hWndDesk, 0, vbNullString, vbNullString)
    
            Dim strText As String
            Dim lngRet As Long
            Do While hWnd <> 0
                strText = String$(100, Chr$(0))
                lngRet = GetClassName(hWnd, strText, 100)
    
                If Left$(strText, lngRet) = "EXCEL7" Then
                    GetExcelObjectFromHwnd hWnd
                    Exit Sub
                End If
    
                hWnd = FindWindowEx(hWndDesk, hWnd, vbNullString, vbNullString)
                Loop
    
            On Error Resume Next
        End If
    
        Exit Sub
    
    MyErrorHandler:
        MsgBox "GetWbkWindows" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Sub
    
    Public Function GetExcelObjectFromHwnd(ByVal hWnd As Long) As Boolean
        On Error GoTo MyErrorHandler
    
        Dim fOk As Boolean
        fOk = False
    
        Dim iid As UUID
        Call IIDFromString(StrPtr(IID_IDispatch), iid)
    
        Dim obj As Object
        If AccessibleObjectFromWindow(hWnd, OBJID_NATIVEOM, iid, obj) = 0 Then 'S_OK
            Dim objApp As Excel.Application
            Set objApp = obj.Application
            Debug.Print objApp.Workbooks(1).Name
    
            Dim myWorksheet As Worksheet
            For Each myWorksheet In objApp.Workbooks(1).Worksheets
                Debug.Print "     " & myWorksheet.Name
                DoEvents
            Next
    
            fOk = True
        End If
    
        GetExcelObjectFromHwnd = fOk
    
        Exit Function
    
    MyErrorHandler:
        MsgBox "GetExcelObjectFromHwnd" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Function
    
        2
  •  9
  •   brettdj    13 年前

    我相信VBA比查尔斯想象的更强大;)

    如果只有一些棘手的方法从 GetObject and CreateObject 我们会解决你的问题!

    编辑:

    Sub Excels()
        Dim currentExcel As Excel.Application
        Dim newExcel As Excel.Application
    
        Set currentExcel = GetObject(, "excel.application")
        Set newExcel = CreateObject("excel.application")
    
        newExcel.Visible = True
        newExcel.Workbooks.Add
        'and so on...
    End Sub
    
        3
  •  8
  •   brettdj    11 年前

    我认为在VBA中,您可以访问另一个正在运行的实例中的应用程序对象 . 如果知道在另一个实例中打开的工作簿的名称,则可以获取对应用程序对象的引用。看到了吗 Allen Waytt's page

    Dim xlApp As Excel.Application
    Set xlApp = GetObject("c:\mypath\ExampleBook.xlsx").Application

    允许我获取一个指向 ExampleBook.xlsx 打开。

    我相信“ExampleBook”应该是完整的路径,至少在Excel2010中是这样的。我目前正在自己尝试,所以我会在得到更多细节后尝试更新。

    如果不同的实例打开了相同的工作簿,但只有一个实例具有写访问权限,那么可能会出现复杂的情况。

        4
  •  7
  •   James MacAdie    10 年前

    多亏了这篇很棒的文章,我有了一个例程来查找当前运行在机器上的所有Excel应用程序的数组。问题是我刚刚升级到64位的Office2013,结果都出了问题。

    ... Declare Function ... 进入之内 ... Declare PtrSafe Function ...

    Option Explicit
    
    #If Win64 Then
    
        Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
        Private Declare PtrSafe Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal Hwnd As LongPtr, ByVal lpClassName As String, ByVal nMaxCount As LongPtr) As LongPtr
        Private Declare PtrSafe Function IIDFromString Lib "ole32" (ByVal lpsz As LongPtr, ByRef lpiid As UUID) As LongPtr
        Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" (ByVal Hwnd As LongPtr, ByVal dwId As LongPtr, ByRef riid As UUID, ByRef ppvObject As Object) As LongPtr
    
    #Else
    
        Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
        Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
        Private Declare Function IIDFromString Lib "ole32" (ByVal lpsz As Long, ByRef lpiid As UUID) As Long
        Private Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hwnd As Long, ByVal dwId As Long, ByRef riid As UUID, ByRef ppvObject As Object) As Long
    
    #End If
    
    Type UUID 'GUID
        Data1 As Long
        Data2 As Integer
        Data3 As Integer
        Data4(7) As Byte
    End Type
    
    Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
    Const OBJID_NATIVEOM As LongPtr = &HFFFFFFF0
    
    ' Run as entry point of example
    Public Sub Test()
    
    Dim i As Long
    Dim xlApps() As Application
    
        If GetAllExcelInstances(xlApps) Then
            For i = LBound(xlApps) To UBound(xlApps)
                If xlApps(i).Workbooks(1).Name <> ThisWorkbook.Name Then
                    MsgBox (xlApps(i).Workbooks(1).Name)
                End If
            Next
        End If
    
    End Sub
    
    ' Actual public facing function to be called in other code
    Public Function GetAllExcelInstances(xlApps() As Application) As Long
    
    On Error GoTo MyErrorHandler
    
    Dim n As Long
    #If Win64 Then
        Dim hWndMain As LongPtr
    #Else
        Dim hWndMain As Long
    #End If
    Dim app As Application
    
        ' Cater for 100 potential Excel instances, clearly could be better
        ReDim xlApps(1 To 100)
    
        hWndMain = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    
        Do While hWndMain <> 0
            Set app = GetExcelObjectFromHwnd(hWndMain)
            If Not (app Is Nothing) Then
                If n = 0 Then
                    n = n + 1
                    Set xlApps(n) = app
                ElseIf checkHwnds(xlApps, app.Hwnd) Then
                    n = n + 1
                    Set xlApps(n) = app
                End If
            End If
            hWndMain = FindWindowEx(0&, hWndMain, "XLMAIN", vbNullString)
        Loop
    
        If n Then
            ReDim Preserve xlApps(1 To n)
            GetAllExcelInstances = n
        Else
            Erase xlApps
        End If
    
        Exit Function
    
    MyErrorHandler:
        MsgBox "GetAllExcelInstances" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    
    End Function
    
    #If Win64 Then
        Private Function checkHwnds(xlApps() As Application, Hwnd As LongPtr) As Boolean
    #Else
        Private Function checkHwnds(xlApps() As Application, Hwnd As Long) As Boolean
    #End If
    
    Dim i As Integer
    
        For i = LBound(xlApps) To UBound(xlApps)
            If xlApps(i).Hwnd = Hwnd Then
                checkHwnds = False
                Exit Function
            End If
        Next i
    
        checkHwnds = True
    
    End Function
    
    #If Win64 Then
        Private Function GetExcelObjectFromHwnd(ByVal hWndMain As LongPtr) As Application
    #Else
        Private Function GetExcelObjectFromHwnd(ByVal hWndMain As Long) As Application
    #End If
    
    On Error GoTo MyErrorHandler
    
    #If Win64 Then
        Dim hWndDesk As LongPtr
        Dim Hwnd As LongPtr
    #Else
        Dim hWndDesk As Long
        Dim Hwnd As Long
    #End If
    Dim strText As String
    Dim lngRet As Long
    Dim iid As UUID
    Dim obj As Object
    
        hWndDesk = FindWindowEx(hWndMain, 0&, "XLDESK", vbNullString)
    
        If hWndDesk <> 0 Then
    
            Hwnd = FindWindowEx(hWndDesk, 0, vbNullString, vbNullString)
    
            Do While Hwnd <> 0
    
            strText = String$(100, Chr$(0))
            lngRet = CLng(GetClassName(Hwnd, strText, 100))
    
            If Left$(strText, lngRet) = "EXCEL7" Then
    
                Call IIDFromString(StrPtr(IID_IDispatch), iid)
    
                If AccessibleObjectFromWindow(Hwnd, OBJID_NATIVEOM, iid, obj) = 0 Then 'S_OK
    
                    Set GetExcelObjectFromHwnd = obj.Application
                    Exit Function
    
                End If
    
            End If
    
            Hwnd = FindWindowEx(hWndDesk, Hwnd, vbNullString, vbNullString)
            Loop
    
            On Error Resume Next
    
        End If
    
        Exit Function
    
    MyErrorHandler:
        MsgBox "GetExcelObjectFromHwnd" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    
    End Function
    
        5
  •  5
  •   user2854823    11 年前

    我也有类似的问题/目标。

    所以我取了他的代码,在GetExcelObjectFromHwnd中放了一个for循环,把1改成了一个计数器。结果是我可以获得所有活动的excel工作簿,并返回我需要跨excel实例访问和访问其他WB的信息。

    Type TargetWBType
        name As String
        returnObj As Object
        returnApp As Excel.Application
        returnWBIndex As Integer
    End Type
    

    对于名称,我只使用基本文件名,例如“example.xls”。这个代码片段通过在目标WB的每个WS上吐出A6的值来证明其功能。像这样:

    Dim targetWB As TargetWBType
    targetWB.name = "example.xls"
    
    Call GetAllWorkbookWindowNames(targetWB)
    
    If Not targetWB.returnObj Is Nothing Then
        Set targetWB.returnApp = targetWB.returnObj.Application
        Dim ws As Worksheet
        For Each ws In targetWB.returnApp.Workbooks(targetWB.returnWBIndex).Worksheets
            MsgBox ws.Range("A6").Value
        Next
    Else
        MsgBox "Target WB Not found"
    End If
    

    所以现在ForEachLoop最初创建的整个模块看起来是这样的,我已经指出了我所做的更改。它确实有一个msgbox弹出窗口,这是我为了调试而留在代码段中的。一旦找到你的目标就把它去掉。代码:

    Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
    Declare Function GetClassName Lib "User32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
    Declare Function IIDFromString Lib "ole32" (ByVal lpsz As Long, ByRef lpiid As UUID) As Long
    Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As UUID, ByRef ppvObject As Object) As Long
    
    Type UUID 'GUID
      Data1 As Long
      Data2 As Integer
      Data3 As Integer
      Data4(7) As Byte
    End Type
    
    '------------- Form Module --------------
    
    Option Explicit
    
    Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
    Const OBJID_NATIVEOM As Long = &HFFFFFFF0
    
    'My code: added targetWB
    Sub GetAllWorkbookWindowNames(targetWB As TargetWBType)
        On Error GoTo MyErrorHandler
    
        Dim hWndMain As Long
        hWndMain = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    
        Do While hWndMain <> 0
            GetWbkWindows hWndMain, targetWB 'My code: added targetWB
            hWndMain = FindWindowEx(0&, hWndMain, "XLMAIN", vbNullString)
        Loop
    
        Exit Sub
    
    MyErrorHandler:
        MsgBox "GetAllWorkbookWindowNames" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Sub
    
    'My code: added targetWB
    Private Sub GetWbkWindows(ByVal hWndMain As Long, targetWB As TargetWBType)
        On Error GoTo MyErrorHandler
    
        Dim hWndDesk As Long
        hWndDesk = FindWindowEx(hWndMain, 0&, "XLDESK", vbNullString)
    
        If hWndDesk <> 0 Then
            Dim hWnd As Long
            hWnd = FindWindowEx(hWndDesk, 0, vbNullString, vbNullString)
    
            Dim strText As String
            Dim lngRet As Long
            Do While hWnd <> 0
                strText = String$(100, Chr$(0))
                lngRet = GetClassName(hWnd, strText, 100)
    
                If Left$(strText, lngRet) = "EXCEL7" Then
                    GetExcelObjectFromHwnd hWnd, targetWB 'My code: added targetWB
                    Exit Sub
                End If
    
                hWnd = FindWindowEx(hWndDesk, hWnd, vbNullString, vbNullString)
                Loop
    
            On Error Resume Next
        End If
    
        Exit Sub
    
    MyErrorHandler:
        MsgBox "GetWbkWindows" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Sub
    
    'My code: added targetWB
    Public Function GetExcelObjectFromHwnd(ByVal hWnd As Long, targetWB As TargetWBType) As Boolean
        On Error GoTo MyErrorHandler
    
        Dim fOk As Boolean
        fOk = False
    
        Dim iid As UUID
        Call IIDFromString(StrPtr(IID_IDispatch), iid)
    
        Dim obj As Object
        If AccessibleObjectFromWindow(hWnd, OBJID_NATIVEOM, iid, obj) = 0 Then 'S_OK
            Dim objApp As Excel.Application
            Set objApp = obj.Application
    
            'My code
            Dim wbCount As Integer
            For wbCount = 1 To objApp.Workbooks.Count
            'End my code
    
                'Not my code
                Debug.Print objApp.Workbooks(wbCount).name
    
                'My code
                    If LCase(objApp.Workbooks(wbCount).name) = LCase(targetWB.name) Then
                        MsgBox ("Found target: " & targetWB.name)
                        Set targetWB.returnObj = obj
                        targetWB.returnWBIndex = wbCount
                    End If
                'End My code
    
                'Not my code
                Dim myWorksheet As Worksheet
                For Each myWorksheet In objApp.Workbooks(wbCount).Worksheets
                    Debug.Print "     " & myWorksheet.name
                    DoEvents
                Next
    
            'My code
            Next
            'Not my code
    
            fOk = True
        End If
    
        GetExcelObjectFromHwnd = fOk
    
        Exit Function
    
    MyErrorHandler:
        MsgBox "GetExcelObjectFromHwnd" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    End Function
    

    我重复一遍,这是可行的,使用TargetWB类型中的变量,我可以跨Excel实例可靠地访问工作簿和工作表。

    我看到的解决方案唯一的潜在问题是,如果您有多个同名的WB。现在,我相信它会返回这个名字的最后一个实例。如果我们在If中添加一个Exit,那么我相信它将返回它的第一个实例。我没有仔细地测试这一部分,因为在我的应用程序中,只有一个打开的文件实例。

        6
  •  0
  •   Steve_m    7 年前

    为了补充James MacAdie的答案,我认为您执行redim太晚了,因为在checkHwnds函数中,您在尝试检查最大值为100的值时,会出现超出范围的错误,即使您尚未完全填充数组?我修改了下面的代码,它现在为我工作。

    ' Actual public facing function to be called in other code
    Public Function GetAllExcelInstances(xlApps() As Application) As Long
    
    On Error GoTo MyErrorHandler
    
    Dim n As Long
    #If Win64 Then
        Dim hWndMain As LongPtr
    #Else
        Dim hWndMain As Long
    #End If
    Dim app As Application
    
    ' Cater for 100 potential Excel instances, clearly could be better
    ReDim xlApps(1 To 100)
    
    hWndMain = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    
    Do While hWndMain <> 0
        Set app = GetExcelObjectFromHwnd(hWndMain)
        If Not (app Is Nothing) Then
            If n = 0 Then
                n = n + 1
                ReDim Preserve xlApps(1 To n)
                Set xlApps(n) = app
            ElseIf checkHwnds(xlApps, app.Hwnd) Then
                n = n + 1
                ReDim Preserve xlApps(1 To n)
                Set xlApps(n) = app
            End If
        End If
        hWndMain = FindWindowEx(0&, hWndMain, "XLMAIN", vbNullString)
    Loop
    
    If n Then
        GetAllExcelInstances = n
    Else
        Erase xlApps
    End If
    
    Exit Function
    
    MyErrorHandler:
        MsgBox "GetAllExcelInstances" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
    
    End Function
    
        7
  •  -4
  •   Charles Williams    14 年前