【问题标题】:Get name of an Excel worksheet containing code获取包含代码的 Excel 工作表的名称
【发布时间】:2014-03-03 19:47:06
【问题描述】:

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

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

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    使用“我”对象。

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

    【讨论】:

      【解决方案2】:

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

      Application.ThisWorkbook 属性 (Excel)

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

      Application.ThisCell 属性 (Excel)

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

      【讨论】:

        【解决方案3】:

        要查询项目的实际代码结构,您需要允许访问 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
        

        【讨论】:

          猜你喜欢
          • 2010-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-22
          相关资源
          最近更新 更多