A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Hi Paul,
See if this suits:
Sub Test()
Dim Sh As Worksheet, Wb As Workbook
Dim NewSh As Worksheet
Dim CodeName As String
CodeName = "MainSheet"
Set Wb = ThisWorkbook
Set Sh = ShByCodename(Wb, CodeName)
' Add new sheet with the required CodeName
If Sh Is Nothing Then
Set Sh = Wb.Sheets.Add
' Set the codename. Note: step by step debugging does not work here!
Sh.[_CodeName] = CodeName
'Set Sh = ShByCodename(Wb, CodeName)
End If
Debug.Print Sh.Name, Sh.CodeName
End Sub
Function ShByCodename(Wb As Workbook, CodeName As String) As WorkSheet
Dim Sh As Object
For Each Sh In Wb.WorkSheets
If StrComp(CodeName, Sh.CodeName) = 0 Then
Set ShByCodename = Sh
Exit Function
End If
Next
End Function
Here is also another version of ShByCodename function with caching of all previously searched sheets:
Function ShByCodename(Wb As Workbook, CodeName As String, Optional ResetCache As Boolean) As WorkSheet
' Return sheet object via its string codename, or Nothing if not found.
' For speed up reason, sheets are cached in the static dictionary object.
' Arguments:
' Wb - workbook object
' CodeName - string codename of the sheet
' [ResetCache] - optional flag to reset all previously cached sheet objects
Dim cn As String, Sh As Object
Static Dic As Object
' Create dictionary object only at first call of this function
If Dic Is Nothing Then
Set Dic = CreateObject("Scripting.Dictionary")
Dic.CompareMode = 1
End If
' Main
With Dic
' Reset the cache if ResetCache = True
If ResetCache And .Count Then .RemoveAll
' See if the sheet is already in the dictionary
If .Exists(CodeName) Then
If Not .Item(CodeName) Is Nothing Then
' Return the found sheet object
Set ShByCodename = .Item(CodeName)
Exit Function
End If
End If
' Create cache of sheets by their codename
For Each Sh In Wb.WorkSheets
cn = Sh.CodeName
Set .Item(Sh.CodeName) = Sh
If StrComp(cn, CodeName) = 0 Then
' Return the found sheet object
Set ShByCodename = Sh
' Comment the next line to cahce all sheets of Wb
Exit Function
End If
Next
End With
End Function
You may also get properties or call methods like this:
ShByCodename(ActiveWorkbook, CodeName).Range("A1").Value = "Hi!"