If you are working in Excel, and you want to show the worksheet name in a Cell on that worksheet, you can use the CELL function to do so.
By default the CELL function will return the current document name, if used with the filename info_type:
This provides a full path to the spreadsheet, with the worksheet of the current Cell at the end, e.g:
You can easily get just the worksheet name by using the FIND and MID functions to do the hard work. You need to find the location of the last square bracket, and find achieves this as shown:
This would return the position of the last bracket. In this case it is at position 22 of the text that CELL(“filename”) returns. The MID function can extract text starting at a location for n length, where n is an arbitrary number. So we would combine MID, FIND and CELL functions to return just the worksheet name like this:
The reason we add a +1 is because we want to start extracting the text one character AFTER the right square bracket, e.g. at the start of the Worksheet name. Our result is:
So far so good, and how is this any different than any other blog post or forum post on the net explaining this? So far it’s not, but here comes the fun part.
What if you have multiple Worksheets, and you do this:
- Have a cell with content, Sheet1!B2
- Sheet1!B2 displays the content of OtherSheet!H5, i.e.:
- You want Sheet1!B1 to display the worksheet name where the CONTENT of Sheet1!B2 comes from.
You could try using the MID/FIND/CELL function combination to try this. In Sheet1!B1 you would enter:
However this would yield the worksheet name of B2 itself, not the worksheet where you are taking your content from:
Not what we wanted. Somehow you need to get the Value of the formula used =OtherSheet!H5 and look up the worksheet name for OtherSheet!H5
To do this you ware going to need to do two things:
- Make a new function to display the formula, sans the equal sign
- Make your CELL function use the result of your function to lookup the filename info_type
We can use the Excel VB Editor to create a new function, and call it GetLocation:
<br /> Function GetLocation(Cell As Range) As String<br /> GetLocation = Mid(Cell.Formula, 2)<br /> End Function<br />
But we can’t just use GetLocation to directly feed the CELL function. We need to use another handy function INDIRECT. This allows us to return the result of the GetLocation function as a Reference. This then allows the CELL function to evaluate the filename/Worksheet details for the destination cell in the other worksheet:
This now provides the Worksheet name of the cell that Sheet1!B1 is using to get it’s content from which is OtherSheet!H5:
This is very handy when you need to show on a master worksheet which other worksheet your data is actually coming from. Windows Excel only, not Mac I’m afraid – until they bring back VB. Enjoy!