简体   繁体   English

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

[英]Adding Sheet Names to Array in Excel VBA

I am trying to add sheet names into an array in Excel VBA using the code below. 我正在尝试使用下面的代码将表单名称添加到Excel VBA中的数组中。 It is only picking up one value (always the last worksheet name). 它只获取一个值(始终是最后一个工作表名称)。 For example, if I have 2 sheets: List1 and List2, it only picks up List2 and shows a blank value for the first sheet. 例如,如果我有2张:List1和List2,它只会拾取List2并显示第一张纸的空白值。 If I add 4, it only shows the 4th, and so on. 如果我添加4,它只显示第4个,依此类推。 I'm not sure why I'm getting blank values. 我不确定为什么我会得到空白的价值观。

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

You should change ReDim ArraySheets(x) to ReDim Preserve ArraySheets(x) 您应该将ReDim ArraySheets(x)更改为ReDim Preserve ArraySheets(x)

When you use just ReDim the contents of the array are not kept, which is why you only get the final sheet name. 当您仅使用ReDim ,不会保留数组的内容,这就是您只获得最终工作表名称的原因。 Using ReDim Preserve re-sizes the array while keeping the contents. 使用ReDim Preserve在保留内容的同时重新调整阵列大小。

Without loops 没有循环

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

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

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