Dim flag As Boolean Private Sub UserForm_Initialize() Dim myWorksheet As Worksheet flag = True With lstSheets .MultiSelect = fmMultiSelectMulti .ListStyle = fmListStyleOption For Each myWorksheet In Worksheets If myWorksheet.Visible = xlSheetVisible Then 'add each visible worksheet to the listbox .AddItem myWorksheet.Name End If Next myWorksheet End With flag = False End Sub Private Sub lstSheets_Change() Dim s As String Dim i As Integer If flag = False Then With lstSheets If .ListCount < 1 Then .Selected(0) = False GoTo errHandler End If End With End If With lstSheets On Error GoTo valueCheck i = .Selected(.ListIndex) 'is -1 on the first call s = '.Selected(.ListIndex).Value If .Selected(i) = True Then On Error GoTo errHandler 'error may occur on the following line Worksheets(s).Visible = False Else: Worksheets(s).Visible = True End If End With Exit Sub errHandler: MsgBox ("There must be at least one visible sheet!") lstSheets.Selected(i) = False Exit Sub valueCheck: Exit Sub End Sub
I made a user form that, with the click of an item in the listbox (which is populated with the worksheet names), will show or hide the matching worksheet. I was using indices, but a problem occurs when there are some hidden sheets to begin with, because the listbox is filled with only the visible worksheets (that's part of the functionality required) and so, when there are hidden worksheets the indices of the listbox are totally different. So, to avoid that kind of bugs I thought I'd use the sheet + listbox names to show/hide the worksheets, but that is proving to be a very hard task.
Can you tell me how I can use the listbox item names + worksheet names to make the "mapping" correctly?