如何通过 VBA 对象名称在另一个工作簿中引用 Excel 工作表?

How to refer to a Excel Worksheet by its VBA Object Name in another Workbook?

我有两本Excel练习册:

  1. Source.xlsx
  2. Tool.xlsm

Source.xlsx 包含具有 VBA 对象名称的工作表 shtTests:

假设在 Tool.xlsm 中我有一个变量,其中包含对存储在 Source.xlsx:

中的工作簿的引用
Dim wkbSource as Workbook
Set wkbSource = GetSourceWorkbook() ' Some function that gives a reference to the workbook

核心问题:如何使用shtTests'[=63=在Tool.xlsm中引用shtTests ] 姓名?


或者将问题表述为代码...假设您有以下代码片段:

Dim wkbSourceShtTests as Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSources)

问题:GetShtTestsFromWkbSources必须是什么样子?


注意:想通过它的Excel名称来引用它,就像你使用[=24一样=] 因为人们可能有一天会更改它的 Excel 名称。

这是你正在尝试的吗?

Sub Sample()
    Dim wbThis As Workbook, wbThat As Workbook
    Dim wsThat As Worksheet
    Dim wsCodeName As String

    Set wbThis = ThisWorkbook
    Set wbThat = Workbooks("Book4") '<~~ Change this to relevant workbook

    wsCodeName = "ShtSheets"

    Set wsThat = wbThat.Worksheets(CStr(wbThat.VBProject.VBComponents(wsCodeName).Properties(7)))

    Debug.Print wsThat.Name
End Sub

注意:为此,您需要启用对 Visual Basic 项目的访问权限

File 菜单上 Excel,单击 Options|Trust Center|Trust Center Settings|Macro Settings,选中复选框 "Trust Access to the VBA Project Object Model"

如果您想要一个功能而不是设置受信任的访问,那么这可能会起作用:

Sub example()
Dim wkbSource As Workbook
Set wkbSource = GetSourceWorkbook()

Dim wkbSourceShtTests As Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSource, "shtTests")

End Sub

Function GetShtTestsFromWkbSources(wkbk As Workbook, codename As String) As Worksheet
For Each sht In wkbk.Sheets
    If sht.codename = codename Then Set GetShtTestsFromWkbSources = sht
Next
End Function