Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully reference a worksheet by codename

Tags:

excel

vba

When I reference Excel worksheets using the CodeName property, how do I fully qualify them including the workbook reference?

I want to guard against a scenario with two different workbooks open and two sheets having the same CodeName. I use ThisWorkbook because I want to reference the workbook the code is running from.

I imagine something like this:

Dim tgWs As Worksheet
Set tgWs = ThisWorkbook.WsSummary
tgWs.Cells(1,1).Value = "Test"

where WsSummary is the sheet's codename.

like image 613
WillborHaven Avatar asked Aug 08 '14 12:08

WillborHaven


People also ask

What is codename in Excel?

The value that you see in the cell to the right of (Name) in the Properties window is the code name of the selected object. At design time, you can change the code name of an object by changing this value. You cannot programmatically change this property at runtime.

How do I reference a cell in VBA?

If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.


1 Answers

Referring to a sheet by its codename always implies the sheet in ThisWorkbook, i.e. the workbook that contains the code you are executing.

There seems to be no straightforward way to fully qualify a sheet in a different workbook using its codename.

This function will help you do this:

Function GetSheetWithCodename(ByVal worksheetCodename As String, Optional wb As Workbook) As Worksheet
    Dim iSheet As Long
    If wb Is Nothing Then Set wb = ThisWorkbook ' mimics the default behaviour
    For iSheet = 1 To wb.Worksheets.Count
        If wb.Worksheets(iSheet).CodeName = worksheetCodename Then
            Set GetSheetWithCodename = wb.Worksheets(iSheet)
            Exit Function
        End If
    Next iSheet
End Function

Example usage:

GetSheetWithCodename("Sheet1", Workbooks("Book2")).Cells(1, 1) = "Sheet1 in Book2"
GetSheetWithCodename("Sheet1", ActiveWorkbook).Cells(1, 1) = "Sheet1 in ActiveWorkbook"
GetSheetWithCodename("Sheet1").Cells(1, 1) = "Sheet1 in ThisWorkbook" 

Note that the last line is equivalent to simply saying:

Sheet1.Cells(1, 1) = "Sheet1 in ThisWorkbook" 

because, as mentioned above, referring to a sheet by its codename always imply the sheet in ThisWorkbook.

like image 152
Jean-François Corbett Avatar answered Oct 17 '22 15:10

Jean-François Corbett