使用VBA循环浏览具有特定名称的工作表

问题描述 投票:0回答:1

我正在尝试构建一个宏来遍历文件,并为每个名为“ File-n”的工作表打开一个用户窗体,其中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

此宏无法识别任何工作表。下面的代码有效,但是我希望尽可能清除它。我不喜欢列出潜在的多达30张纸。

If WS.Name = "File-0" or WS.Name = "File-1" or WS.Name = "File-2" or ... Then
excel vba excel-vba worksheet
1个回答
0
投票

为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

0
投票

您可以将Like用作注释中提到的@BigBen,也可以使用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

0
投票

您的代码的问题是indx已声明但未递增。

应该是

Dim WS As Worksheet
Dim indx As Integer

indx = 1
For Each WS In ThisWorkbook.Worksheets
    WS.Activate
    If WS.Name = "File-" & indx Then
        WS.Select
        userform1.show
    End If
    indx = indx + 1 '\\Increment indx
Next WS
© www.soinside.com 2019 - 2024. All rights reserved.