在Excel VBA中将数据表名称添加到数组中

我正在尝试使用下面的代码将表名添加到Excel VBA中的数组中。 它只提取一个值(总是最后的工作表名称)。 例如,如果我有两个工作表:List1和List2,它只拾取List2并为第一个工作表显示空白值。 如果我加4,它只显示第4个,依此类推。 我不知道为什么我得到空白值。

Dim curSheet As Worksheet Dim ArraySheets() As String Dim x As Variant For Each curSheet In ActiveWorkbook.Worksheets If curSheet.Name Like "*List*" Then ReDim ArraySheets(x) ArraySheets(x) = curSheet.Name x = x + 1 End If Next curSheet 

您应该将ReDim ArraySheets(x)更改为ReDim Preserve ArraySheets(x)

当您只使用ReDim时,数组的内容不会保留,这就是为什么您只能得到最终的表名。 使用ReDim Preserve在保留内容的同时重新调整数组的大小。

没有循环

 Sub GetNAmes() Dim strIn As String Dim X strIn = Application.InputBox("Search string", "Enter string to find", "*List*", , , , , 2) If strIn = "False" Then Exit Sub ActiveWorkbook.Names.Add "shtNames", "=RIGHT(GET.WORKBOOK(1),LEN(GET.WORKBOOK(1))-FIND(""]"",GET.WORKBOOK(1)))" X = Filter([index(shtNames,)], strIn, True, 1) Select Case UBound(X) Case Is > 0 strIn = Application.InputBox(Join(X, Chr(10)), "Multiple matches found - type position to select", , , , , 1) If strIn = "False" Then Exit Sub On Error Resume Next Sheets(CStr(X(strIn))).Activate On Error GoTo 0 Case 0 Sheets(X(0)).Activate Case Else MsgBox "No match" End Select End Sub