获取包含代码的Excel工作表的名称

我有驻留在页面上的代码并引用工作簿的内容。 当从不同的工作表执行时,我想要获取包含代码的特定工作表的名称。

我有包含数据的工作表。 该代码被添加到该工作表和运行 – 这会产生一个摘要工作表。 从摘要工作表中,我想运行数据工作表上的代码。 这意味着我不能使用ActiveSheet ,我将不得不按名称引用数据表。

如何获得包含代码的工作表的名称,而不必对名称进行硬编码?

有2个应用程序属性会让你感兴趣。

Application.ThisWorkbook属性(Excel)

返回一个Workbook对象,该对象表示当前macros代码正在运行的工作簿。 只读。

Application.ThisCell属性(Excel)

返回从Range对象中调用用户定义的函数的单元格。

使用“我”对象。

Me.Name是您寻找的财产,无论活动工作表,它都会给您包含代码的工作表的名称。

要查询项目的实际代码结构,您需要允许访问VBA项目对象模型(Excel设置>信任中心>macros设置,然后添加对Microsoft Visual Basic for Application Extensibility vX的引用),其中vX是5.3 。 您可以使用这个对象来标识哪些表单中包含哪些代码。

不过,我build议以另一种方式来做。

而是遍历工作簿中的工作表,然后在错误包装器中使用Application.Run运行macros

请注意,重构代码并将其全部放在标准模块中,然后作为参数传入工作表将是更好的做法(请参阅我的第二个示例)

例如:

 'With code distributed in each worksheet Sub blah() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets On Error Resume Next Application.Run ws.CodeName & ".CollectInfoMacro" If Err.Number = 1004 Then Debug.Print "Skipping "; ws.Name; ", No macro defined" On Error GoTo 0 Next ws End Sub 'Otherwise, better practice would be to refactor 'and not have code on each sheet, instead in a standard module: Sub blahblah() Dim ws As Worksheet Dim results As Collection Set results = New Collection For Each ws In ThisWorkbook.Worksheets If ws.Name <> "Summary" Then 'or whatever results.Add getYourInfoForTheSummary(ws), ws.Name End If Next ws 'Process your results (ie dump to the summary worksheet etc) ... End Sub Function getYourInfoForTheSummary(ws As Worksheet) As Collection 'or return whatever Dim results As Collection Set results = New Collection With ws 'do something End With Set getYourInfoForTheSummary = results 'or whatever End Function