Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - How can I determine the sheet name in a workbook that my function is sitting?

Imagine I have a xls workbook containing 3 tabs, SheetA, SheetB, and SheetC. I want to write a simple VBA function that returns the name of the sheet where the function is called.

Function SheetName as String
    SheetName = ???
End Function

So if I call =SheetName() in Tab SheetB, it will ALWAYS return SheetB.

Note:

 ActiveSheet.Name

doesn't work because if you are on the SheetA and calculate the workbook, it will return SheetA.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This works:

Function SheetName as String
    SheetName = Application.Caller.Worksheet.Name
End Function

I should mention that as a practical matter, you should be very cautious about using caller-sensitive features like this in any function. Later on when you (or worse, someone else) are trying to debug something, it can be a real nightmare if you don't realize that that the function acts differently when called from code or in the debugger/immediate window, than it does in actual use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...