简体   繁体   中英

VBA Select Multiple Worksheets Macro

I spent some time searching for an answer but had no luck.

I'm trying to create a macro that will select multiple worksheets based on user input from an input box and combine it with a LIKE operator to select all the worksheets at once. Each of these sheets has a different name but all begin with a 5 digit number, 20001 for example, that I can use as a criteria for selection.

I can get this to work if I hard code the 5 digit value and select multiple sheets at once but can't get it to work with the input box value. I've tried different iterations of entering the input box value/variable but haven't had any luck.

Example Below with input box:

Public Sub SixPayTest()
    Dim Bunumber As String
    Dim ws As Worksheet

    Bunumber = Application.InputBox("Enter BU #")

    For Each ws In ActiveWorkbook.Sheets
       If ws.Name Like bunumber Then ws.Select (False)
    Next ws
End Sub

This Working example below will select all the worksheet I need it to but without the input box:

Public Sub SixPayTest()
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Sheets
       If ws.Name Like "*20001*" Then ws.Select (False)
    Next ws
End Sub

You need to add wildcards for like value. For example:

If ws.Name Like "*" & bunumber & "*" Then
    ....

Even clearer would be to update value before like conditon.

bunumber="*" & bunumber & "*"

Also, if you want to find sheet with name starting with bnumber, do not add first star "*" to the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM