[英]Adding Sheet Names to Array in Excel VBA
我正在嘗試使用下面的代碼將表單名稱添加到Excel VBA中的數組中。 它只獲取一個值(始終是最后一個工作表名稱)。 例如,如果我有2張: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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.