I have two Excel Workbooks:
Source.xlsx
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.
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"
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.