使用 VBA 遍历具有特定名称的工作表
Using VBA to Loop Through Sheets with a Specific Name
我正在尝试通过文件为 运行 构建一个宏,并为名称为 "File-n" 的每个 sheet 打开一个用户窗体,其中 n 是一个整数。我试过这段代码,但它不起作用:
Dim WS As Worksheet
Dim indx As Integer
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name = "File-" & indx Then
WS.Select
userform1.show
End If
Next WS
此宏无法识别任何 sheet。下面的代码有效,但我希望尽可能清理它。我不喜欢列出最多 30 个 sheet 的潜在数量。
If WS.Name = "File-0" or WS.Name = "File-1" or WS.Name = "File-2" or ... Then
为 indx 添加一个循环
Dim WS As Worksheet
Dim indx As Integer
For i = 1 to 30
indx = i
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name = "File-" & i Then
userform1.show
End If
Next WS
Next i
您可以像@BigBen 在评论中提到的那样使用 Like
或像下面这样使用 Instr
:
Option Explicit
Sub test()
Dim WS As Worksheet
Dim indx As Integer
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If InStr(1, LCase(WS.Name), "file") Then
WS.Select
UserForm1.Show
End If
Next WS
End Sub
看看下面的代码是否有帮助
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name Like "File-*" Then
WS.Select
userform1.show
End If
Next WS
我正在尝试通过文件为 运行 构建一个宏,并为名称为 "File-n" 的每个 sheet 打开一个用户窗体,其中 n 是一个整数。我试过这段代码,但它不起作用:
Dim WS As Worksheet
Dim indx As Integer
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name = "File-" & indx Then
WS.Select
userform1.show
End If
Next WS
此宏无法识别任何 sheet。下面的代码有效,但我希望尽可能清理它。我不喜欢列出最多 30 个 sheet 的潜在数量。
If WS.Name = "File-0" or WS.Name = "File-1" or WS.Name = "File-2" or ... Then
为 indx 添加一个循环
Dim WS As Worksheet
Dim indx As Integer
For i = 1 to 30
indx = i
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name = "File-" & i Then
userform1.show
End If
Next WS
Next i
您可以像@BigBen 在评论中提到的那样使用 Like
或像下面这样使用 Instr
:
Option Explicit
Sub test()
Dim WS As Worksheet
Dim indx As Integer
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If InStr(1, LCase(WS.Name), "file") Then
WS.Select
UserForm1.Show
End If
Next WS
End Sub
看看下面的代码是否有帮助
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
WS.Activate
If WS.Name Like "File-*" Then
WS.Select
userform1.show
End If
Next WS