1

I am trying to build a macro to run through a file and open a userform for every sheet that has the name "File-n" where n is an integer. I've tried this code, but it doesn't work:

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

This macro doesn't recognize any sheets. The code below works, but I was hoping to clean it up if possible. I don't like listing out the potential number of sheets up to thirty.

If WS.Name = "File-0" or WS.Name = "File-1" or WS.Name = "File-2" or ... Then
Teamothy
  • 2,000
  • 3
  • 16
  • 26
  • Possibly an easier approach - do you have any sheets with names starting with `"File-"` that you *don't* want to consider? – BigBen Dec 04 '19 at 15:15
  • @BigBen No, all sheets with the name "File-" would be relevant in this case. – chrisphils26 Dec 04 '19 at 15:18
  • 3
    Then just use `InStr` (see the posted answer), or `Left` even. – BigBen Dec 04 '19 at 15:19
  • 1
    Try to avoid `.Activate` and `.Select` if not expressly needed for user communication - c.f. [How to avoid using Select in Excel VBA?](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba?r=SearchResults&s=1|191.2192) – T.M. Dec 06 '19 at 14:48

3 Answers3

3

You can use Like as @BigBen mentioned in comment or use Instr like below:

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
Teamothy
  • 2,000
  • 3
  • 16
  • 26
2

See if below code helps

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
shrivallabha.redij
  • 5,832
  • 1
  • 12
  • 27
0

Add one more loop for 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
Pablo G
  • 199
  • 12
  • 1
    If you were to do this approach, the outer loop should be the worksheet loop, and the inner loop should be `i`. But... it's really inefficient and there are way better approaches. – BigBen Dec 04 '19 at 15:47