[英]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. 想象一下,我有一个xls工作簿,其中包含3个选项卡SheetA,SheetB和SheetC。 I want to write a simple VBA function that returns the name of the sheet where the function is called.
我想编写一个简单的VBA函数,该函数返回调用该函数的工作表的名称。
Function SheetName as String
SheetName = ???
End Function
So if I call =SheetName() in Tab SheetB, it will ALWAYS return SheetB. 因此,如果我在Tab SheetB中调用= SheetName(),它将始终返回SheetB。
Note: 注意:
ActiveSheet.Name
doesn't work because if you are on the SheetA and calculate the workbook, it will return SheetA. 不起作用,因为如果您在SheetA上计算工作簿,它将返回SheetA。
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.
稍后,当您(或更糟糕的是,其他人)尝试调试某些内容时,如果您没有意识到从代码或在调试器/即时窗口中调用该函数时,它的行为有所不同,那将是一场噩梦。在实际使用中。
You could do something like this: 您可以执行以下操作:
Function sheetName(rng As Range) As String
sheetName = rng.Parent.Name
End Function
Just pass the range the sheet is calling from (even the same range the formula is in). 只需传递工作表调用的范围(甚至与公式所在的范围相同)即可。
In sheet1, 在工作表1中,
=sheetName(A1)
returns Sheet1 返回Sheet1
In Sheet2 在Sheet2中
=sheetName(Sheet1!A1)
Returns Sheet1 as well. 也返回Sheet1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.