VBA - 获取工作簿数量时出错

时间:2016-06-28 09:22:58

标签: excel vba

我在计算正确数量的已打开工作簿时遇到问题。

具体来说,我的数据库中有一个很大的excel文件。我有一个软件的其他数据(运动结果),我导出它们。所以我打开了我的数据库,以及许多其他工作簿(“Workbook1”,“Workbook2”,...),每个锦标赛都有一个工作簿。

我的最终目标是按工作簿将工作簿循环到copy/paste数据库中的数据。 但是当我使用MsgBox(workbooks.counts)时,它只返回“1”。

你知道为什么吗?我错过了什么?

提前致谢,

1 个答案:

答案 0 :(得分:0)

我不知道你是否还有兴趣,但我在很多个月前从网上拿了一些代码(道歉,我不再提供参考)并为此目的修改了它获取所有Excel实例中的所有工作簿。

它可能对您或他人有用。 API声明为32位,因此您必须在必要时修改它们。

Option Explicit
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 AccessibleObjectFromWindow Lib "oleacc" _
    (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As GUID, _
    ByRef ppvObject As Object) As Long

Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
End Type

Public Sub RunMe()
    Dim bks As Collection

    Set bks = GetAllWorkbooks
    MsgBox bks.Count
End Sub

Private Function GetAllWorkbooks() As Collection
    Dim id As GUID
    Dim hWnd As Long
    Dim hDesk As Long
    Dim hXL As Long
    Dim obj As Object
    Dim app As Application
    Dim wb As Workbook

    Set GetAllWorkbooks = New Collection

    'Define GUID values
    'hard codes IDispatch {00020400-0000-0000-C000-000000000046}
    With id
        .Data1 = 132096
        .Data4(0) = 192
        .Data4(7) = 70
    End With

    'Loop through excel window handles to find applications
    hWnd = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
    Do While hWnd > 0
        hDesk = FindWindowEx(hWnd, 0&, "XLDESK", vbNullString)
        hXL = FindWindowEx(hDesk, 0&, "EXCEL7", vbNullString)
        If AccessibleObjectFromWindow(hXL, &HFFFFFFF0, id, obj) = &H0 Then
            'Populate return collection with the workbooks
            Set app = obj.Application
            For Each wb In app.Workbooks
                GetAllWorkbooks.Add wb
            Next
        End If
        hWnd = FindWindowEx(0&, hWnd, "XLMAIN", vbNullString)
    Loop
End Function