Need code for "if sheet exist, do certain code; if not, stop this macro"

dener123

New Member
Joined
Jul 10, 2024
Messages
18
Office Version
  1. 2021
Hey guys!

I need a code that determines what to do when sheet name "Jan" exists;

If exists; select sheet "Jan" and run certain code.
If it does not exist; stop this macro.


Thank you :)
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
Off the top of my head, perhaps

VBA Code:
Dim sht as sheet

For each sht in thisworkbook.sheets
    If sht.name = "Jan" then
        do something
    Else
        exit sub
next

Use worksheets (not sheets) if you want to skip chart sheets.
 
Upvote 0
I was in a hurry to go out. That is not correct as it will exit as soon as it encounters one sheet that is not named "Jan"
VBA Code:
For each sht in thisworkbook.sheets
    If sht.name = "Jan" then
        'do stuff
    End If
next
If Jan does not exist, nothing happens as long as no code that follows does anything else. Otherwise the sub will just terminate.
 
Upvote 0
Just another option..
VBA Code:
If Evaluate("isref('" & "Jan" & "'!A1)") Then
' rest of code here
End If
 
Upvote 0
Solution
Learning something new every day! Can you please explain why the concatenation rather than evaluate("isref(Jan!A1)"). Perhaps it's just personal preference?
 
Upvote 0
Can you please explain why the concatenation rather than evaluate("isref(Jan!A1)"). Perhaps it's just personal preference?

Laziness really, I am used to using a variable where the "Jan" is
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

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