Hauke P.
Hauke P.

Reputation: 2823

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

I have two Excel Workbooks:

  1. Source.xlsx
  2. Tool.xlsm

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

Screenshot of VBA Properties for 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.

Upvotes: 2

Views: 5108

Answers (2)

CLR
CLR

Reputation: 12254

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

Upvotes: 1

Siddharth Rout
Siddharth Rout

Reputation: 149287

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"

Upvotes: 3

Related Questions