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

℡╲_俬逩灬. 提交于 2020-07-09 12:09:21

问题


I have two Excel Workbooks:

  1. Source.xlsx
  2. Tool.xlsm

Source.xlsx contains a Worksheet with the VBA Object Name shtTests:

Let's assume that in Tool.xlsm I have a variable that contains a reference to the Workbook stored in Source.xlsx:

Dim wkbSource as Workbook
Set wkbSource = GetSourceWorkbook() ' Some function that gives a reference to the workbook

Core Question: How can I reference shtTests within Tool.xlsm by using shtTests' VBA Name?


Or to formulate the question as code... assume you have this code snippet:

Dim wkbSourceShtTests as Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSources)

Question: What does GetShtTestsFromWkbSources have to look like?


Note: I do not want to reference it by its Excel Name like you would do using wkbSources.Worksheets("Test Cloning") because people might change its Excel Name some day.


回答1:


If you wanted a function instead of setting up the trusted access then this would probably work:

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



回答2:


Is this what you are trying?

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

Note: For this to work, you need to enable access to Visual Basic Projects

On the File menu Excel, Click Options|Trust Center|Trust Center Settings|Macro Settings, Check the box "Trust Access to the VBA Project Object Model"



来源:https://stackoverflow.com/questions/44776975/how-to-refer-to-a-excel-worksheet-by-its-vba-object-name-in-another-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!