【问题标题】:Excel VBA Counting and Storing List of All Open WorkbooksExcel VBA计数和存储所有打开工作簿的列表
【发布时间】:2017-12-20 21:00:52
【问题描述】:

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

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

【问题讨论】:

  • 我也用 Windows.Count 替换了它,没用。
  • 试试for each b in application.workbooks
  • 我试过 For Each b In Application.Workbooks MsgBox (CStr(b.Name)) Next b 但没有运气,仍然只显示带有按钮的工作簿。
  • 工作簿是否在不同的应用程序中打开? (例如,下载的工作簿通常会在完全不同的 Excel 应用程序中打开)
  • 好的,我会修改我的问题来问这个。

标签: vba excel count


【解决方案1】:

这是一个如何完成的示例(无 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

【讨论】:

  • 友情提示:您重新调整了 Arr(1 To 100, 1 To 2),但将您的 1-100 项分配到第二维;认为这是正确的:Arr(i, 1) = .NameArr(i, 2) = .Path &amp; "\" &amp; .Name。顺便说一句,此示例中不需要 SearchFor$
  • 是的,我知道,这是我根据需要更改的重复使用代码,结果必须是第一维中的索引,这通常是不切实际的,因为除非最后一维,否则 redim 不起作用.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多