Refer to worksheet's codename

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,832
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
I have a master workbook which opens data workbooks.

Each data workbook only contains two worksheets.

The names of the worksheets in each data workbook are different but their codenames are static, say wksyear1 and wksyear2.

How can I refer to the data workbooks' worksheets by its codename?

This code doesn't work because it doesn't know what wksyear1 is.

Code:
Dim ws As Worksheet

Set ws = Workbooks(FileName.Name).Worksheets(wksyear1))

Thanks
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
It is easy to use the sheet code name for the active workbook.
For using a different workbook, you may have to loop through the sheets first to find the codename, then set the sheet variable


VBA Code:
Sub getSheetName()
    Dim wb As Workbook, s As String, ws As Worksheet, sh As Worksheet
    Set wb = Workbooks("TrialSheet.xlsx")
    s = "Sheet1"  'sheet codename to find
    With wb
        For Each sh In .Sheets
            If sh.CodeName = s Then
                Set ws = .Sheets(sh.Name)
                Exit For
            End If
        Next
    End With
    MsgBox ws.Name
    ws.Range("D1") = "Hello"
End Sub
 
Upvote 0
You can use an iterating function like this :
VBA Code:
Function GetWorksheet(ByVal wb As Workbook, ByVal sSheetCodeName As String) As Worksheet
    Dim ws As Worksheet
    For Each ws In wb.Sheets
        If ws.CodeName = sSheetCodeName Then
            Set GetWorksheet = ws: Exit Function
        End If
    Next ws
End Function

Then call it like this:
VBA Code:
Dim ws As Worksheet
Set ws = GetWorksheet(Workbooks(Filename.Name), "wksyear1")
 
Upvote 0

Forum statistics

Threads
1,214,920
Messages
6,122,279
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top