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

问题描述 投票:0回答:2

我希望尝试计算当前打开的工作簿数量。 Workbooks.Count将无法工作,因为并非所有文件都在同一个Excel应用程序实例中。当文件在下载后打开时,它在excel的新实例中,因此Workbooks不包含它。

有没有办法为每个正在运行的Excel实例获取所有工作簿的计数?

excel vba excel-vba count
2个回答
0
投票

here回答了类似的问题。答案也适用于这种情况。


0
投票

这是一个如何完成它的例子(没有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
© www.soinside.com 2019 - 2024. All rights reserved.