Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
538 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Using sheet codenames in Microsoft Excel VBA |
---|
Do your macros keep falling over due to users renaming their worksheets in Excel? Read this article to find out if sheet codenames could be the solution you need. |
A common way to reference Excel worksheets in Visual Basic for Applications (VBA) is to use their tab name. However, this alternative method has several advantages - and one disadvantage!
In the images below, the first shows the view you are likely to get when looking at the Visual Basic Editor for a workbook with default tab names for the sheets, and the second shows the view you would have when a user has modified the name of the first worksheet:
Tab names unchanged | Tab name modified on first sheet |
When referring to the first sheet in your VBA code, you would have to use the following lines of code respectively:
Worksheets("Sheet1").Select
Worksheets("January").Select
However, if a user subsequently modified the tab name again - to "JanSales", for instance - then the existing code would generate a run-time error as VBA would not be able to find the sheet.
In order to avoid this common problem, you can use the sheet's codename (the codename is the part that remained as Sheet1 in the two examples above) in your VBA code, as shown below:
Sheet1.Select
This isn't hugely descriptive though - but you can change this codename as follows:
Changing the codename:
You can now refer to this sheet simply by typing the following in your code:
JanSales.Select
...and no matter what users do to the tab name or the order of the worksheets, any mention of JanSales will always take you to that worksheet.
Codename as JanSales | New tab name doesn't matter |
The only drawback of using this naming strategy is that a sheet's codename cannot be used when referring to it from a macro in another spreadsheet - in this scenario you would have to use the tab name.
Some other pages relevant to the above blog include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.