7

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

我有包含数据的工作表。代码被添加到该工作表并运行 - 生成一个摘要工作表。从摘要工作表中,我想在数据工作表上运行代码。这意味着我不能使用ActiveSheet,我必须按名称引用数据表。

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

4

3 回答 3

8

使用“我”对象。

Me.Name 是您寻求的属性,它会为您提供包含代码的工作表的名称,而不管活动工作表。

于 2014-03-03T11:47:06.627 回答
7

有 2 个应用程序属性会让您对此感兴趣。

Application.ThisWorkbook属性 (Excel)

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

Application.ThisCell属性 (Excel)

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

于 2013-08-08T16:48:01.743 回答
0

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

但是,我建议以另一种方式进行。

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

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

例如:

'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 (i.e. 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
于 2013-08-08T15:35:02.203 回答