Search code examples
excelvba

Excel VBA asking user to select worksheet


Main objective is to select a Sheet from my workbook, example I have Sheet 1 to 10, the user will be requested to select only 1 sheet. Below is a sample of a code that I found whereby it will open a box to let user select a worksheet cell instead of a worksheet. I am not sure how I can add photos to show, but I will try my best to explain. Example a box appears, I must type in =Sheet1!$E$4 for it to work instead of just typing in =Sheet1. Any help is appreciated.

    On Error Resume Next
    Set ws2 = Application.InputBox(Prompt:="Select a worksheet", Title:="Select Worksheet", Type:=8).Parent
    On Error GoTo 0
    If ws2 Is Nothing Then
        MsgBox "User cancelled...", vbInformation
    Else

Solution

  • Input sheet name as String and check if it is a valid object.

        ws2_name = Application.InputBox(prompt:="Select a worksheet", Title:="Select Worksheet")
        On Error Resume Next
        Set ws2 = Worksheets(ws2_name)
        On Error GoTo 0
        If IsEmpty(ws2) Then
            MsgBox "User cancelled (or name error)...", vbInformation
            Exit Sub
        End If
        'here is code process
        ws2.Select
    
    

    Mod on the comment

    sh_list = "Select a sheet:"
    For i = 1 To Worksheets.Count
        sh_list = sh_list & Chr(10) & Worksheets(i).Name
    Next i
        ws2_name = Application.InputBox(prompt:=sh_list, Title:="Select Worksheet")
        On Error Resume Next
        Set ws2 = Worksheets(ws2_name)
        On Error GoTo 0
        If IsEmpty(ws2) Then
            MsgBox "User cancelled (or name error)...", vbInformation
            Exit Sub
        End If
        ws2.Select
    

    This will list the available sheet names in the input box. A more refined workaround can be a ListBox in a Userform.