Problem looping through sheets via vba

Engineer Joe

Well-known Member
Joined
Jun 10, 2005
Messages
549
VBA Code:
    For Each sht In ThisWorkbook.Sheets
        If sht.Name Like "DHU - *" Then
            sht.Visible = xlSheetVisible
        End If
    Next sht

I've got this code that keeps erroring out on mismatch 13. I'm not sure what's causing it. It gets through the loop like 8 times and then says that "sht" is nothing...and i've still got like 30 sheets to go. Maybe charts are causing it? Any help would be appreciated.
 

Excel Facts

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.
Is this code in the workbook you are running it against, or another one?
Are all the "DHU" sheets hidden or visible at the beginning when the code is first initiated?
 
Upvote 0
Change the code to
VBA Code:
For Each Sht In ThisWorkbook.Worksheets
I guess worksheets is defined as non-chart sheets
 
Upvote 1
Hi @Engineer Joe. Thanks for posting on the forum.

Maybe charts are causing it?
That's right, the problem, as @Jeffrey Mahoney commented, is because a chart isn't really a sheet.
But if you had a hidden chart sheet and wanted to make it visible with For Each Sht In ThisWorkbook.Worksheets it won't work.

But if that's the case and you need to make sheets or charts visible, then declare sht as object, then it works for both:

Rich (BB code):
Sub shvisible_2()
  Dim sht As Object
  For Each sht In ThisWorkbook.Sheets
    If sht.Name Like "DHU - *" Then
      sht.Visible = xlSheetVisible
    End If
  Next sht
End Sub

--------------
Let me know the result and I'll get back to you as soon as I can.
Sincerely
Dante Amor
--------------
 
Upvote 0
Solution

Forum statistics

Threads
1,223,891
Messages
6,175,229
Members
452,621
Latest member
Laura_PinksBTHFT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top