[英]How to refer to the workbook where a function is used in Excel VBA?
I have created a user-defined function called SheetAtIndex
that returns the name of the sheet at the specified index in a workbook. 我创建了一个名为
SheetAtIndex
的用户定义函数,它返回工作簿中指定索引处的工作表名称。
At first I used ActiveWorkbook.Sheets(Index).Name
to get the name of the sheet. 起初我使用
ActiveWorkbook.Sheets(Index).Name
来获取工作表的名称。 Anytime I switch to another open workbook the results became messed up. 无论何时我切换到另一个打开的工作簿,结果都搞砸了。 No surprise there.
这并不奇怪。
ThisWorkbook.Sheets(Index).Name
worked for some time till I realized I have to duplicate the code in every workbook that needs the UDF. ThisWorkbook.Sheets(Index).Name
工作了一段时间,直到我意识到我必须在每个需要UDF的工作簿中复制代码。 In addition every file that needs the function must be saved as a macro-enable workbook 此外,每个需要该函数的文件都必须保存为启用宏的工作簿
Final decision : Put the function in my personal macro book. 最终决定 :将该功能放入我的个人宏书中。
Problem : How to reference the workbook/worksheet where the function will be called from? 问题 :如何引用将从中调用函数的工作簿/工作表?
A UDF can get a reference to the cell that called it with Application.ThisCell
UDF可以获取对使用
Application.ThisCell
调用它的单元格的引用
Once you have a reference to the calling cell, you can get the worksheet ( .WorkSheet
) and workbook ( .WorkSheet.Parent
) from there 一旦你有一个对调用单元格的引用,你可以从那里得到工作表(
.WorkSheet
)和工作簿( .WorkSheet.Parent
)
Function SheetAtIndex(Index As Variant) As String
SheetAtIndex = Application.ThisCell.Worksheet.Parent.Worksheets(Index).Name
End Function
Or, to get a reference to the Worksheet 或者,获取对工作表的引用
Function SheetAtIndex(Index As Variant) As Worksheet
Set SheetAtIndex = Application.ThisCell.Worksheet.Parent.Worksheets(Index)
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.