-
If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.
-
Thread starter
J Ericson
-
Start date
Feb 11, 2009
-
#1
What is the proper syntax to verify an active worksheets name?
If the ActiveSheet name = Sheet1 name Then …
Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
-
#2
If ActiveSheet.Name = «Sheet1» Then
End If
-
#3
try this
If ActiveSheet.Name = Worksheets(1).Name Then
‘do stuff
End If
-
#4
Duh! Could it have been any easier.
Thanks for the help!
J Ericson
Yard
Well-known Member
-
#5
ginisimo, don’t forget that if you change your worksheet name in Excel you’ll need to adjust your code as well (since «Sheet1» is hard-coded). Safer option IMO is to use the Worksheet.Codename property.
-
#6
my bad. I read it as if he wanted to check if the name was «Sheet1» not that it matched Sheets(1).Name
- Threads
- 1,192,536
- Messages
- 5,993,056
- Members
- 440,469
- Latest member
- Quaichlek
Здравствуйте!
Ребята, как выглядит условие если лист активен, пытаюсь таким образом
Здравствуйте!
Ребята, как выглядит условие если лист активен, пытаюсь таким образом
Сообщение Здравствуйте!
Ребята, как выглядит условие если лист активен, пытаюсь таким образом
Источник
If activesheet is called X, then do y
LinkBack
Thread Tools
Rate This Thread
Display
If activesheet is called X, then do y
I need some VBA that says if the active sheet is «dogs», then call macro
entitled get dogs. If active sheet is «cats», then call macro entitled
«get Cats».
Re: If activesheet is called X, then do y
Assuming everything exists..
Run ActiveSheet.Name
Charles
xl Geek
Darin Kramer wrote:
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible.
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
Re: If activesheet is called X, then do y
One way I think will work is:
if activesheet.name = «dogs» then GetDogs
if activesheet.name = «cats» then GetCats
However, when is this code supposed to run. Is it based on anytime the
sheet is active, or is it dependent on some other code that runs?
If it is to run any time those sheets are activated then you could add code
specifically to that sheet.
For example:
Right-click on sheet «dogs» and select View code. Click General dropdown
and select Worksheet. Click other dropdown and make sure it is on
Activate».
Then in your code, enter the macro name you want to run when this sheet is
selected. Here’s what it would look like:
Private Sub Worksheet_Activate()
GetDogs
End Sub
«Darin Kramer» wrote in message
news:u6yYVkktGHA.2020@TK2MSFTNGP03.phx.gbl.
>
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible.
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
Re: If activesheet is called X, then do y
One way I think will work is:
if activesheet.name = «dogs» then GetDogs
if activesheet.name = «cats» then GetCats
However, when is this code supposed to run. Is it based on anytime the
sheet is active, or is it dependent on some other code that runs?
If it is to run any time those sheets are activated then you could add code
specifically to that sheet.
For example:
Right-click on sheet «dogs» and select View code. Click General dropdown
and select Worksheet. Click other dropdown and make sure it is on
Activate».
Then in your code, enter the macro name you want to run when this sheet is
selected. Here’s what it would look like:
Private Sub Worksheet_Activate()
GetDogs
End Sub
«Darin Kramer» wrote in message
news:u6yYVkktGHA.2020@TK2MSFTNGP03.phx.gbl.
>
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible.
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
Re: If activesheet is called X, then do y
Oops I forgot the «get»
Run «get» & Activesheet.Name
I eliminated the space because I don’t think excel will let you have a
space in a macro name.
Charles
xl Geek
Die_Another_Day wrote:
> Assuming everything exists..
> Run ActiveSheet.Name
>
> Charles
> xl Geek
>
> Darin Kramer wrote:
> > Hi guys,
> >
> > I need some VBA that says if the active sheet is «dogs», then call macro
> > entitled get dogs. If active sheet is «cats», then call macro entitled
> > «get Cats».
> >
> > Possible.
> >
> > Thanks!!
> >
> > D
> >
> >
> > *** Sent via Developersdex http://www.developersdex.com ***
Re: If activesheet is called X, then do y
I had forgotten to take out a line. Here is the version that works. Sorry
about that.
Источник
VBA Select Sheet, Activate Sheet, and Get Activesheet
In this Article
This article will discuss the ActiveSheet object in VBA. It will also discuss how to activate, select, and go to Worksheets (& much more). Read our full VBA Worksheets Guide for more information about working with worksheets in VBA.
ActiveSheet
In VBA, ActiveSheet refers to the currently active Worksheet. Only one Sheet may be active at a time.
Activate Worksheet (Setting the ActiveSheet)
To set the ActiveSheet use Worksheet.Activate:
The Activate Sheet command will actually “go to” the sheet, changing the visible Sheet.
The above example uses the Sheet (Tab) name. Instead you can use the VBA code name for the worksheet:
ActiveSheet Name
To get the ActiveSheet Name:
Selected Sheets vs ActiveSheet
At any point in time, only one Sheet can be the ActiveSheet. However, multiple Worksheets can be selected at once.
When multiple Worksheets are selected only the “top-most” Worksheet is considered active (the ActiveSheet).
Select Worksheet
If you would like to select a worksheet instead of activating it. Use .Select instead.
Select Worksheet by Tab Name
This selects a Worksheet based on it’s Sheet Tab Name
Select Worksheet by Index Number
This selects a Worksheet based on it’s position relative to other tabs
Select Worksheet With VBA Code Name
Selecting worksheets by code name can prevent errors caused by worksheet name changes.
Select Current Worksheet
To select the current Worksheet, use the ActiveSheet object:
More Activate / Select Sheet Examples
Set ActiveSheet to Variable
This will assign the ActiveSheet to a Worksheet Object Variable.
Change ActiveSheet Name
With ActiveSheet
Using the With Statement allows you to streamline your code when working with objects (such as Sheets or ActiveSheet).
Notice how you don’t need to repeat “ActiveSheet” before each line of code. This can be a huge time saver when working with a long list of commands.
Loop Through Selected Sheets
The following macro will Loop through all selected sheets, displaying their names.
GoTo Next Sheet
This code will go to the next Sheet. If the ActiveSheet is the last Sheet, then it will go to the first Sheet in the Workbook.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Active Sheet & Select Sheet in Excel VBA
In this post, you’ll be learning how you can select a worksheet and activate it using Excel VBA.
ActiveSheet in Excel
The term ActiveSheet, refers to the currently active Worksheet in Excel VBA.
Let’s see in detail about the active sheet command.
To run the code,
- Under the developer tab, click visual basic
- Click the insert option and choose module
- Enter your code and click run.
How to Activate or Set the WorkSheet in Excel VBA?
To set the ActiveSheet use Worksheet.Activate:
This sheet will activate a new worksheet in the current workbook.
If you want to activate an existing sheet,
ActiveSheet Name
To get the ActiveSheet Name, use the property ActiveSheet.name in Excel VBA.
Selected Sheets vs ActiveSheet in Excel VBA
At any point in time, only one Sheet can be the ActiveSheet in Excel VBA.But, multiple Worksheets can be selected at once.
If multiple Worksheets are selected, then the Worksheet with top most priority is considered as active sheet.
Select Worksheet
If you want to select a worksheet instead of activating it you can use .select in the above codes instead of activate command.
Select Worksheet by Tab Name
This code line selects a Worksheet based on its Sheet Tab Name
Select Worksheet by Index Number
This code line selects a Worksheet based on its position relative to other tabs
Select Worksheet with VBA Code Name
To select worksheet using VBA code name, enter the following code
Selecting worksheets by code name will prevent errors.
Select Current Worksheet
To select the current Worksheet, you can use the ActiveSheet object:
Change ActiveSheet Name
To change the active sheet name
GoTo Next Sheet
To go to next sheet, enter the following code. If the active sheet is the last sheet, this command will go to the first sheet.
Источник
VBA Get Sheet Name / Rename Sheet
In this Article
This tutorial will cover interacting with Sheet names in VBA.
Get Sheet Name
Sheet names are stored in the Name property of the Sheets or Worksheets object. The Sheet Name is the “tab” name that’s visible at the bottom of Excel:
Get ActiveSheet Name
This will display the ActiveSheet name in a message box:
Get Sheet Name by index Number
This will display the first worksheet name in a message box:
This will display the name of the last worksheet in the workbook:
Get Sheet Name by Code Name
In the VBA Editor, there is an option to change the “code name” of a Sheet. The code name is not visible to the Excel user and can only be seen in the VBA Editor:
In VBA, when working with Sheets, you can reference the usual Tab name:
or the VBA code name:
Referencing the code name is desirable in case the Sheet tab name ever changes. If you allow you Excel user access to changing sheet names you should reference the code name in your VBA code so that a Sheet tab name mismatch doesn’t cause an error. Sheet code names are discussed in more detail here.
To get the Sheet name using the VBA Code name, do the following:
Rename Sheet
You can rename Sheets by adjusting the name property of the Sheets or Worksheets object.
Rename ActiveSheet
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Rename Sheet by Name
Rename Sheet by Sheet Index Number
Here we use 1 to rename the first Sheet in the Workbook.
Rename Sheet by Code Name
This code will rename a sheet using it’s VBA code name (discussed above):
Check if Sheet Name Exists
The function will return TRUE if the Sheet exists, or FALSE if it does not.
Copy Sheet and Rename
This example is from our article on Copying Sheets.
After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename a copied Sheet, simply use ActiveSheet.Name:
Note: We added error handling to avoid errors if the Sheet name already exists.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Adblock
detector
neira Пользователь Сообщений: 76 |
#1 08.01.2019 12:38:08 Доброго времени суток! Есть код:
Запускает макроса в зависимости от текста в ячейке. Мне нужно что-то похожее, но условием должно быть имя листа. Если лист «1» запустить макрос1, если лист «2», запустить макрос2. Или, быть может, на номер листа по порядку (но лучше по имени). Изменено: neira — 08.01.2019 12:38:39 |
||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#2 08.01.2019 12:42:05
Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
neira, запускайте соответствующий макрос при активации соответствующего листа — прописать в модуле листа. <#0> |
neira Пользователь Сообщений: 76 |
Ігор Гончаренко, спасибо. Задним умом хочу спросить, можно ли сделать такой макрос? Если имя листа равно «1» запустить макрос1 |
vikttur Пользователь Сообщений: 47199 |
#5 08.01.2019 13:06:42
|
||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#6 08.01.2019 13:17:57
имя какого листа нужно сравнить с «1»? Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
neira Пользователь Сообщений: 76 |
#7 08.01.2019 16:46:16
Хочу заменить 4 строчку с «если имя активного листа равно 2» на «если имя активного листа не равно 1». Изменено: neira — 08.01.2019 18:05:29 |
||||
БМВ Модератор Сообщений: 21376 Excel 2013, 2016 |
#8 08.01.2019 16:53:53
По вопросам из тем форума, личку не читаю. |
||
В четвёртой строке вместо If напишите Else и больше ничего. Изменено: Михаил С. — 08.01.2019 16:57:58 |
|
neira Пользователь Сообщений: 76 |
#10 08.01.2019 18:03:19 Спасибо большое! |
-
08-02-2006, 11:40 AM
#1
If activesheet is called X, then do y
Hi guys,
I need some VBA that says if the active sheet is «dogs», then call macro
entitled get dogs. If active sheet is «cats», then call macro entitled
«get Cats».Possible…?
Thanks!!
D
*** Sent via Developersdex http://www.developersdex.com ***
-
08-02-2006, 11:45 AM
#2
Re: If activesheet is called X, then do y
Assuming everything exists..
Run ActiveSheet.NameCharles
xl GeekDarin Kramer wrote:
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible…?
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
-
08-02-2006, 11:45 AM
#3
Re: If activesheet is called X, then do y
One way I think will work is:
if activesheet.name = «dogs» then GetDogs
if activesheet.name = «cats» then GetCatsHowever, when is this code supposed to run. Is it based on anytime the
sheet is active, or is it dependent on some other code that runs?
If it is to run any time those sheets are activated then you could add code
specifically to that sheet.
For example:Right-click on sheet «dogs» and select View code. Click General dropdown
and select Worksheet. Click other dropdown and make sure it is on
Activate».
Then in your code, enter the macro name you want to run when this sheet is
selected. Here’s what it would look like:Private Sub Worksheet_Activate()
GetDogs
End SubHTH,
Paul«Darin Kramer» <darin_kramer@hotmail.com> wrote in message
news:u6yYVkktGHA.2020@TK2MSFTNGP03.phx.gbl…
>
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible…?
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
-
08-02-2006, 12:00 PM
#4
Re: If activesheet is called X, then do y
One way I think will work is:
if activesheet.name = «dogs» then GetDogs
if activesheet.name = «cats» then GetCatsHowever, when is this code supposed to run. Is it based on anytime the
sheet is active, or is it dependent on some other code that runs?
If it is to run any time those sheets are activated then you could add code
specifically to that sheet.
For example:Right-click on sheet «dogs» and select View code. Click General dropdown
and select Worksheet. Click other dropdown and make sure it is on
Activate».
Then in your code, enter the macro name you want to run when this sheet is
selected. Here’s what it would look like:Private Sub Worksheet_Activate()
GetDogs
End SubHTH,
Paul«Darin Kramer» <darin_kramer@hotmail.com> wrote in message
news:u6yYVkktGHA.2020@TK2MSFTNGP03.phx.gbl…
>
> Hi guys,
>
> I need some VBA that says if the active sheet is «dogs», then call macro
> entitled get dogs. If active sheet is «cats», then call macro entitled
> «get Cats».
>
> Possible…?
>
> Thanks!!
>
> D
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
-
08-02-2006, 12:20 PM
#5
Re: If activesheet is called X, then do y
Oops I forgot the «get»
Run «get» & Activesheet.Name
I eliminated the space because I don’t think excel will let you have a
space in a macro name.Charles
xl Geek
Die_Another_Day wrote:
> Assuming everything exists..
> Run ActiveSheet.Name
>
> Charles
> xl Geek
>
> Darin Kramer wrote:
> > Hi guys,
> >
> > I need some VBA that says if the active sheet is «dogs», then call macro
> > entitled get dogs. If active sheet is «cats», then call macro entitled
> > «get Cats».
> >
> > Possible…?
> >
> > Thanks!!
> >
> > D
> >
> >
> > *** Sent via Developersdex http://www.developersdex.com ***
-
08-02-2006, 02:50 PM
#6
Re: If activesheet is called X, then do y
I had forgotten to take out a line. Here is the version that works. Sorry
about that.Sub fill_in()
ActiveSheet.Range(«A3»).Select
For Each cell In Sheets
Do
If ActiveCell > «» ThenElseIf ActiveCell.Offset(0, 3) > «» Then
ActiveCell = ActiveCell.Offset(-1, 0)ElseIf ActiveCell = «» And ActiveCell.Offset(1, 0) = «» Then
Exit For
End If
ActiveCell.Offset(1, 0).Activate
Loop
Next
End Sub—
Best wishes,Jim
«PCLIVE» wrote:
> One way I think will work is:
>
> if activesheet.name = «dogs» then GetDogs
> if activesheet.name = «cats» then GetCats
>
> However, when is this code supposed to run. Is it based on anytime the
> sheet is active, or is it dependent on some other code that runs?
> If it is to run any time those sheets are activated then you could add code
> specifically to that sheet.
> For example:
>
> Right-click on sheet «dogs» and select View code. Click General dropdown
> and select Worksheet. Click other dropdown and make sure it is on
> Activate».
> Then in your code, enter the macro name you want to run when this sheet is
> selected. Here’s what it would look like:
>
> Private Sub Worksheet_Activate()
> GetDogs
> End Sub
>
>
> HTH,
> Paul
>
>
> «Darin Kramer» <darin_kramer@hotmail.com> wrote in message
> news:u6yYVkktGHA.2020@TK2MSFTNGP03.phx.gbl…
> >
> > Hi guys,
> >
> > I need some VBA that says if the active sheet is «dogs», then call macro
> > entitled get dogs. If active sheet is «cats», then call macro entitled
> > «get Cats».
> >
> > Possible…?
> >
> > Thanks!!
> >
> > D
> >
> >
> > *** Sent via Developersdex http://www.developersdex.com ***
>
>
>
In this article you will be learning about sheets vs worksheets in excel VBA and how to use of these functions when manipulating spreadsheets.
Table of Contents
- Difference between Worksheets and Sheets in VBA
- Sheets
- Looping through each Object in the Sheets collection
- Looping through every Sheet in the Sheets collection
- Worksheets
- Referencing a Worksheet in VBA
- Using the Worksheet Name
- Using the Index Number
- Using the Worksheet Code Name
- Referring to a Worksheet in a Different Workbook
- Adding a Worksheet
- Deleting a Worksheet
- Delete a specific worksheet.
- Renaming the Worksheets
- Adding Multiple Sheets
- Assigning Worksheet Object to a Variable
- Hide Worksheets Using VBA
- To unhide the sheets
- Hide Sheets Based on the Text in it
- Sorting the Worksheets in an Alphabetical Order
- Creating a Table of Contents of All Worksheets with Hyperlinks
- Referencing a Worksheet in VBA
Difference between Worksheets and Sheets in VBA
In VBA, you have two collections that can be a bit confusing at times. In a workbook, you can have worksheets and as well as chart sheets.
In Excel VBA:
- The ‘Worksheets’ collection would refer to the collection of all the worksheet objects in a workbook.
- The ‘Sheets’ collection would refer to all the worksheets as well as chart sheets in the workbook.
To run the VBA code in Excel, perform the following first
- Under the developer tab, click visual basic
- Click the insert option and choose a module
- Enter your codes and click run.
Now we know, ‘sheets’ is the collection of worksheets and chart sheets.
Looping through each Object in the Sheets collection
To loop through every sheet,
Code:
Sub UsingObject() Dim obj As Object For Each obj In ActiveWorkbook.Sheets MsgBox obj.Name Next obj End Sub
Looping through every Sheet in the Sheets collection
We can also count the sheets, then loop using a For loop.
Code
Sub UsingCount() Dim i As Integer For i = 1 To Sheets.Count MsgBox Sheets(i).Name Next i End Sub
This method of looping by counting the objects will work equally well with Charts and Worksheets.
Worksheets
When you have to work with worksheets only, use the ‘Worksheets’ collection, and when you have to refer to all sheets, then use the ‘Sheets’ collection.
Let’s see worksheets in detail.
Referencing a Worksheet in VBA
You can refer a worksheet in the following methods.
Using the Worksheet Name
This is the easiest way to refer to a worksheet.
When you are working with a workbook with three worksheets namely Sheet 1, Sheet 2, Sheet 3 (which is common in any excel file) and you want to activate Sheet 3.
Use the following code:
Code:
Sub ActivateSheet() Worksheets("Sheet3").Activate End Sub
You can also use the sheets collection method to activate the sheets, as we are using the name of the sheet as the key point.
Use this code
Code:
Sub ActivateSheet() Sheets("Sheet3").Activate End Sub
Using the Index Number
The difficult part of using the name of the sheet to refer them is you need to know the exact name of the sheet or the program doesn’t work.
In this case, you can use the index number of the worksheets. The indexing starts from 1 in the collection of sheets.
Use this code to activate Sheet3:
Code
Sub ActivateSheet() Worksheets(3).Activate End Sub
Important: A chart sheet is not a part of the worksheets collection.
This is because when we use the index numbers in the Worksheet collection, it will only refer to the worksheets in the workbook.
Note: Indexing goes from left to right. So if you shift Sheet3 to the left of Sheet2, then Worksheets (2) would refer to Sheet3.
Using the Worksheet Code Name
You can use the code name of the worksheet to refer to a worksheet. This code name can be assigned in the VB Editor and it won’t change when you change the name of the worksheet.
To give your worksheet a code name, follow these steps:
- Under the Developer tab, click the Visual Basic option.
- This will open the VB Editor.
- Now, Click the View option in the menu and click on Project Window.
- Click on the sheet name in the project explorer that you want to rename.
- In the Properties pane, change the name in the field in front of (Name).
Note: Don’t include spaces in the name.
This would change the name of your Worksheet in the VBA, i.e., the code name. Therefore, when you change the worksheet name it doesn’t affect the code in your VBA.
Now, you can use either the Worksheets collection to refer to the worksheet or use the codename.
The following code uses both worksheet collection method and name of the sheet method.
Code
Worksheets("Sheet3").Activate SH3.Activate
(I have code named my sheet as SH3)
Referring to a Worksheet in a Different Workbook
If you need to access a worksheet in a different workbook,
Code
Sub SheetActivate() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate End Sub
Adding a Worksheet
When you need to add a worksheet
Code
Sub AddSheet() Worksheets.Add End Sub
Deleting a Worksheet
When you want to delete a worksheet:
Code
Sub DeleteSheet() ActiveSheet.Delete End Sub
Click ok on the warning prompt. The worksheet gets deleted.
To avoid the warning prompt, use the below code:
Code
Sub DeleteSheet() Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End Sub
Note: You can’t undo this delete option. So be sure.
Delete a specific worksheet.
If you want to delete a specific sheet,
Code
Sub DeleteSheet() Worksheets("Sheet3").Delete End Sub
You can also use the code name of the sheet to delete it.
Sub DeleteSheet() SH3.Delete End Sub
Renaming the Worksheets
When you want to rename the sheets using VBA code:
Sub RenameSheet() Worksheets("Sheet1").Name = "Naming sheet" End Sub
Code
Adding Multiple Sheets
When you need to add multiple sheets
Code
Sub RenameSheet() Dim Countsheets As Integer Countsheets = Worksheets.Count For i = 1 To 4 Worksheets.Add after:=Worksheets(Countsheets + i – 1) Worksheets(Countsheets + i).Name = "Multiple Sheets 1" & i Next i End Sub
Assigning Worksheet Object to a Variable
You can assign a worksheet to an object variable, and then use the variable instead of the worksheet references.
Code
Sub RenameSheet() Dim Ws As Worksheet For Each Ws In Worksheets Ws.Name = "Assigning Variable " & Ws.Name Next Ws End Sub
Hide Worksheets Using VBA
You can hide and unhide worksheets using VBA. Normally when a worksheet is hidden, you can easily unhide the worksheet by right-clicking on any sheet tab.
But if you don’t want to unhide the worksheet in this method, you can do this using VBA.
The code below would hide all the worksheets in the workbook (except the active sheet), such that you cannot unhide it by right-clicking on the sheet name.
Code
Sub HideAllExcetActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden Next Ws End Sub
If you want to hide sheets that can be unhidden easily, use the below code.
Code
Sub HideAllExceptActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetHidden Next Ws End Sub
To unhide the sheets
Code:
Sub UnhideAllWoksheets() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets Ws.Visible = xlSheetVisible Next Ws End Sub
Hide Sheets Based on the Text in it
You can hide sheets based on the text in it. You can do this using the VBA INSTR function.
The below code would hide all the sheets except the ones with the text 2020 in it.
Code:
Sub HideWithMatchingText() Dim Ws As Worksheet For Each Ws In Worksheets If InStr(1, Ws.Name, "2020", vbBinaryCompare) = 0 Then Ws.Visible = xlSheetHidden End If Next Ws End Sub
Sorting the Worksheets in an Alphabetical Order
Using VBA, you can quickly sort the worksheets based on their names.
Use the below code to quickly sort sheets in an ascending order.
Code
Sub SortSheetsTabName() Application.ScreenUpdating = False Dim ShCount As Integer, i As Integer, j As Integer ShCount = Sheets.Count For i = 1 To ShCount – 1 For j = i + 1 To ShCount If Sheets(j).Name < Sheets(i).Name Then Sheets(j).Move before:=Sheets(i) End If Next j Next i Application.ScreenUpdating = True End Sub
Creating a Table of Contents of All Worksheets with Hyperlinks
To create a table of contents of all worksheets:
Code
Sub AddIndexSheet() Worksheets.Add ActiveSheet.Name = "Index" For i = 2 To Worksheets.Count ActiveSheet.Hyperlinks.Add Anchor:=Cells(i – 1, 1), _ Address:="", SubAddress:=Worksheets(i).Name & "!A1", _ TextToDisplay:=Worksheets(i).Name Next i End Sub
The above code inserts a new worksheet and names it Index.
It then loops through all the worksheets and creates a hyperlink for all the worksheets in the Index sheet.
Return to VBA Code Examples
In this Article
- ActiveSheet
- Activate Worksheet (Setting the ActiveSheet)
- ActiveSheet Name
- Selected Sheets vs ActiveSheet
- Select Worksheet
- Select Worksheet by Tab Name
- Select Worksheet by Index Number
- Select Worksheet With VBA Code Name
- Select Current Worksheet
- More Activate / Select Sheet Examples
- Set ActiveSheet to Variable
- Change ActiveSheet Name
- With ActiveSheet
- Loop Through Selected Sheets
- GoTo Next Sheet
- VBA Coding Made Easy
This article will discuss the ActiveSheet object in VBA. It will also discuss how to activate, select, and go to Worksheets (& much more). Read our full VBA Worksheets Guide for more information about working with worksheets in VBA.
ActiveSheet
In VBA, ActiveSheet refers to the currently active Worksheet. Only one Sheet may be active at a time.
Activate Worksheet (Setting the ActiveSheet)
To set the ActiveSheet use Worksheet.Activate:
Worksheets("Input").Activate
The Activate Sheet command will actually “go to” the sheet, changing the visible Sheet.
The above example uses the Sheet (Tab) name. Instead you can use the VBA code name for the worksheet:
Sheet1.Activate
ActiveSheet Name
To get the ActiveSheet Name:
msgbox ActiveSheet.name
Selected Sheets vs ActiveSheet
At any point in time, only one Sheet can be the ActiveSheet. However, multiple Worksheets can be selected at once.
When multiple Worksheets are selected only the “top-most” Worksheet is considered active (the ActiveSheet).
Select Worksheet
If you would like to select a worksheet instead of activating it. Use .Select instead.
Select Worksheet by Tab Name
This selects a Worksheet based on it’s Sheet Tab Name
Sheets("Input").Select
Select Worksheet by Index Number
This selects a Worksheet based on it’s position relative to other tabs
Worksheets(1).Select
Select Worksheet With VBA Code Name
Sheet1.Select
Selecting worksheets by code name can prevent errors caused by worksheet name changes.
Select Current Worksheet
To select the current Worksheet, use the ActiveSheet object:
ActiveSheet.Select
More Activate / Select Sheet Examples
VBA Programming | Code Generator does work for you!
Set ActiveSheet to Variable
This will assign the ActiveSheet to a Worksheet Object Variable.
Dim ws As Worksheet
Set ws = ActiveSheet
Change ActiveSheet Name
This will change the ActiveSheet Name.
ActiveSheet.Name = "NewName"
With ActiveSheet
Using the With Statement allows you to streamline your code when working with objects (such as Sheets or ActiveSheet).
With ActiveSheet
.Name = "StartFresh"
.Cells.Clear
.Range("A1").Value = .Name
End With
Notice how you don’t need to repeat “ActiveSheet” before each line of code. This can be a huge time saver when working with a long list of commands.
Loop Through Selected Sheets
The following macro will Loop through all selected sheets, displaying their names.
Sub GetSelectedSheetsName()
Dim ws As Worksheet
For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws
End Sub
GoTo Next Sheet
This code will go to the next Sheet. If the ActiveSheet is the last Sheet, then it will go to the first Sheet in the Workbook.
If ActiveSheet.Index = Worksheets.Count Then
Worksheets(1).Activate
Else
ActiveSheet.Next.Activate
End If
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
<<Return to VBA Examples
In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.
This is extremely valuable in many situations as we will see in the examples later in this tutorial.
To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.
The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).
In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.
But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Syntax – IF Then Else
Below is the generic syntax of If Then Else construct in VBA
IF condition Then true_code [Else false_code]
Or
IF condition Then true_code Else false_code End IF
Note that the Else part of this statement is optional.
Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.
The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.
However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.
When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.
Hence you need to use the End IF statement.
In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”
Examples of Using IF Then Statement in VBA
To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).
Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).
Then you can use the following code:
Sub CheckScore() If Range("A1").Value >=35 Then MsgBox "Pass" End Sub
The above code has a single line of IF statement that checks the value in cell A1.
If it’s more than 35, it shows the message – “Pass”.
If it’s less than 35, nothing happens.
But what if you want to show a message in both the cases, whether a student passed or failed the exam.
The below code would do this:
Sub CheckScore() If Range("A1").Value >= 35 Then MsgBox "Pass" Else MsgBox "Fail" End If End Sub
The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).
But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.
Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.
Nested IF Then (Multiple IF Then statements)
So far we have used a single IF Then statement.
In case you have multiple conditions to check, you can use:
- Multiple IF conditions
- If Then Else statement
- IF Then ElseIf Else construct
Let me show you how these differ and how to use this in Excel VBA.
Multiple IF Then Statements
Let’s take the same example of using a student’s score.
If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.
We can use the below code to get this done:
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" If Range("A1").Value >= 35 Then MsgBox "Pass" End Sub
You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).
In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.
So even if the first IF statement is correct, the second would still be evaluated.
IF Then Else Statement
Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.
If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.
We can use the below code to get this done:
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" Else If Range("A1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End If End Sub
In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.
So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.
IF Then ElseIf Else Statement
The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.
Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End Sub
The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.
Using AND and OR in IF Then Else
So far in this tutorial, we have only checked for a single condition at a time.
However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.
Below is the syntax of using AND/OR condition with the IF Then statement.
IF Condition1 AND Condition2 Then true_code Else false_code End IF
In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.
With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.
Now let’s see how AND and OR statement work with the IF Then Else construct.
Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:
- Fail – When the score is less than 35 in any of the subjects.
- Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
- Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.
Here is the code that will do this:
Sub CheckScore() If Range("A1").Value < 35 Or Range("B1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value < 80 And Range("B1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End Sub
The above code uses both OR and AND statements.
You can also write this same code with a slight change (using OR instead of AND).
Sub CheckScore() If Range("A1").Value < 35 Or Range("B1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value > 80 Or Range("B1").Value > 80 Then MsgBox "Pass, with Distinction" Else MsgBox "Pass" End If End Sub
Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).
Using Not Equal to in If Then
In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.
You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.
To see a practical example of using <>, have a look at Example 1 below.
Using If Then Else with Loops in VBA
So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.
If I need to grade students, I can easily do that using Excel functions.
So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.
Example 1 – Save and Close All Workbooks Except The Active Workbook
If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,
Sub SaveCloseAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks On error resume next If wb.Name <> ActiveWorkbook.Name Then wb.Save wb.Close End If Next wb End Sub
The above code would save and close all the workbooks (except the active one).
It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.
If the name is not the same as that of the Active workbook, it saves and closes it.
In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).
Example 2 – Highlight Cells with Negative Values
Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.
Sub HighlightNegativeCells() Dim Cll As Range For Each Cll In Selection If Cll.Value < 0 Then Cll.Interior.Color = vbRed Cll.Font.Color = vbWhite End If Next Cll End Sub
The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.
Example 3 – Hide All the Worksheet Except the Current Worksheet
In case you want to quickly hide all the worksheets except the active one, you can use the below code:
Sub HideAllExceptActiveSheet() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If ws.Name <> ActiveSheet.Name Then ws.Visible = xlSheetHidden Next ws End Sub
The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.
Example 4 – Extract the Numeric Part from an Alphanumeric String
If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:
Function GetNumeric(CellRef As String) Dim StringLength As Integer StringLength = Len(CellRef) For i = 1 To StringLength If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1) Next i GetNumeric = Result End Function
This code will create a custom function in Excel that can use within the worksheet (just like a regular function).
Where to Put the VBA Code?
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel Tutorials:
- How to Record a Macro in Excel.
- Working with Cells and Ranges in Excel VBA.
- Working with Worksheets in Excel VBA.
- Working with Workbooks in Excel VBA.
- Creating a Custom Function in Excel Using VBA.
- Excel VBA Events – An Easy (and Complete) Guide.
- Excel VBA MsgBox
- How to Run a Macro in Excel.
- How to Create and Use an Excel Add-in.
- Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
- Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
- How to Use Excel VBA InStr Function (with practical EXAMPLES).