简体   繁体   English

所有打开的工作簿的Excel VBA计数和存储列表

[英]Excel VBA Counting and Storing List of All Open Workbooks

I am looking to try and count the current number of workbooks that are opened. 我希望尝试计算打开的工作簿的当前数量。 Workbooks.Count will not work because not all of the files are in the same Excel application instance. Workbooks.Count将不起作用,因为并非所有文件都在同一Excel应用程序实例中。 When the file is opened after being downloaded, its in a new instance of excel, so Workbooks does not include it. 下载后打开文件时,该文件位于excel的新实例中,因此Workbooks不包含它。

Is there a way to get the count of all workbooks for every instance of Excel that is running? 有没有一种方法可以获取正在运行的每个Excel实例的所有工作簿的数量?

here is an example how it can be done (no API): 这是一个示例(不使用API​​)如何完成:

Public Function ListAllExcelWB(Optional ByVal SearchFor$) As Variant() 'exept this one
On Error Resume Next

 If SearchFor = vbNullString Then SearchFor = "*.*"

Dim xl As Excel.Application
Dim Wb As Workbook
Dim Status As Long
Dim Arr()
ReDim Arr(1 to 2, 1 To 100)
Dim i&

Do
  Err.Clear
  Set xl = GetObject(, "Excel.Application")
  Status = Err.Number
  If Status = 0 Then
      'xl.Visible = True
      For Each Wb In xl.Workbooks
            With Wb
                  If .Name <> ThisWorkbook.Name Then
                    i = i + 1
                    Arr(1, i) = .Name 
                    Arr(2, i) = .Path & "\" & .Name
                    If i > 99 Then Status = 1
                  Else: Status = 1 'stoppe la loop si se trouve soi meme, car au niveau des stack, l'instance active est la derniere
                  End If
            End With
      Next

  End If
Loop Until Status <> 0 '= 429

If i > 0 Then
      ReDim Preserve Arr(1 to 2,1 To i)
Else: Erase Arr 'ReDim Arr(0 To 0)
End If

Err.Clear: On Error GoTo 0

Set xl = Nothing: Set Wb = Nothing
ListAllExcelWB = Arr
Erase Arr
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM