API reference · Others
Get_WS_Codename
Looks up a worksheet in ThisWorkbook by its VBA CodeName.
Signature#
Function Get_WS_Codename(ByVal sName As String) As WorksheetParameters#
| Parameter | VBA type | Default | Description |
|---|---|---|---|
sName | StringByVal | Required | Worksheet VBA CodeName to match. This is not necessarily the visible sheet-tab Name. |
Returns#
Worksheet object for the first matching worksheet in ThisWorkbook, or Nothing when no match is found.
Example#
Before
Illustrative workbookValues / state
No array dimensions
| Item | Value |
|---|---|
| First worksheet CodeName | “Feuil1” |
| Visible sheet name | “Transactions” |
After
Returned Worksheet objectValues / state
No array dimensions
| Item | Value |
|---|---|
| CodeName | “Feuil1” |
| Name | “Transactions” |
Sheet names here are illustrative. The code uses the actual first worksheet’s CodeName. This returns an object reference, not a new array or a renamed sheet.
Shaded headers are array indices, not data. Quoted cells are text. Values shown are derived from the source, not an Excel execution.
Option Explicit
Public Sub ExampleOthersGetWorksheet()
Dim utility As New Others
Dim target As Worksheet
If ThisWorkbook.Worksheets.Count = 0 Then Exit Sub
Set target = utility.Get_WS_Codename(ThisWorkbook.Worksheets(1).CodeName)
If Not target Is Nothing Then Debug.Print target.Name
End SubBehavior and edge cases#
- Searches ThisWorkbook.Worksheets in collection order, from index 1 through Count, and stops at the first CodeName equal to sName.
- Uses ThisWorkbook, the workbook containing the VBA code. It does not search ActiveWorkbook or all open workbooks.
- The module has no Option Compare declaration, so its ordinary string equality uses VBA binary comparison; CodeName matching is case-sensitive in this source.
- Only Worksheet objects are considered. Chart sheets are outside the Worksheets collection. A missing match leaves the function result as Nothing; callers should check it before using the returned object.
- Does not alter sheet names, CodeNames, worksheet contents or the active sheet. Use Set to assign its object result.
Performance#
O(w) CodeName comparisons for w worksheets in ThisWorkbook, with O(1) explicit auxiliary state.
View implementation
Function Get_WS_Codename(ByVal sName As String) As Worksheet
Dim lCount As Long
For lCount = 1 To ThisWorkbook.Worksheets.Count
If sName = ThisWorkbook.Worksheets(lCount).CodeName Then
Set Get_WS_Codename = ThisWorkbook.Worksheets(lCount)
Exit For
End If
Next lCount
End Function