在Excel VBA中将工作表名称添加到数组
我试图使用下面的代码在Excel VBA中的数组中添加工作表名称。它只是拾取一个值(总是最后一个工作表名称)。例如,如果我有2张表:List1和List2,它只会拾取List2并显示第一张表的空白值。如果我添加4,它只显示第4,依此类推。我不知道为什么我得到空值。
I am trying to add sheet names into an array in Excel VBA using the code below. 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. If I add 4, it only shows the 4th, and so on. 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
您应该更改 ReDim ArraySheets(x)
to ReDim保留ArraySheets(x)
您只使用 ReDim
数组的内容不保留,这就是为什么只能获得最终的工作表名称。使用 ReDim Preserve
重新调整数组的大小,同时保留内容。
When you use just ReDim
the contents of the array are not kept, which is why you only get the final sheet name. Using ReDim Preserve
re-sizes the array while keeping the contents.