[英]Excel VBA Counting and Storing List of All Open Workbooks
我希望尝试计算打开的工作簿的当前数量。 Workbooks.Count
将不起作用,因为并非所有文件都在同一Excel应用程序实例中。 下载后打开文件时,该文件位于excel的新实例中,因此Workbooks
不包含它。
有没有一种方法可以获取正在运行的每个Excel实例的所有工作簿的数量?
这是一个示例(不使用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.