简体   繁体   English

如何确定函数所在的工作簿中的工作表名称?

[英]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.

相关问题 如何在我的工作簿中的每张纸上运行这个 VBA 代码? - How can I run this VBA code across each sheet in my workbook? 如何将工作表名称作为变量添加到我的数据框中 - how can I add the sheet name to my data frame as a variable 如何确定 Excel 工作簿中有多少个工作表? - How can I determine how many worksheets there are in an Excel workbook? 如何将Excel工作表复制到窗口不可见的工作簿中? - How can I copy an Excel sheet into a workbook whose windows are not visible? 如何在另一个不活动的工作簿中添加工作表 - How can i add a sheet in another workbook that not active 我如何控制将一张纸复制到另一张工作簿中的位置 - How can i control the position to copy one sheet into another workbook 如何将csv加载为当前工作簿的表格? - How can I load a csv as a sheet of the current workbook? 如何将工作表复制到新的未创建的工作簿? - How can I copy a sheet to a new uncreated workbook? 如何使用VBA取消隐藏工作簿中的每个Excel工作表? - How can I Unhide every Excel sheet in a workbook using VBA? 如何在整个工作簿的其余部分但仅在每张工作表上的选定单元格范围内在 2 种货币 USD 和 AED @rate 3.68 之间进行转换? - How can I convert between 2 currencies USD and AED @rate of 3.68 throughout the rest of my workbook but only in selected cell ranges on each sheet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM