如何通过代码名称而不是(选项卡)名称来引用工作表?
我已经尝试过:
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("CodeName")
Dim wsn As String
wsn = ActiveSheet.CodeName
以及我不再拥有的各种其他方法, 由于我删除了不起作用的代码。
如果删除注释行,它确实很短。
'This Function converts a worksheet's code name to its (Tab) name,
'which circumvents errors occurring in the event
'the Worksheets tab name has being changed.
'Original code by me, Quartz_au.
Public Function NameFromCodeName(ByVal inCodeName As String) As String
On Error GoTo CanNotFind
'Assign NameFromCodeName the worksheet's (Tab) Name.
NameFromCodeName = ThisWorkbook.VBProject.VBComponents(inCodeName) _
.Properties("Name").Value
GoTo ExitHere
CanNotFind:
MsgBox "No Worksheet exists with the Code Name: """ & inCodeName & """" _
& Chr(13) & Chr(13) & "Step through code to locate the call." _
, vbCritical + vbOKOnly, "Get Worksheet Name Error"
Stop 'Step through code to locate the call the triggered the error.
ExitHere:
On Error GoTo 0
End Function 'NameFromCodeName
'################################# TESTER #################################
Private Sub TEST_NameFromCodeName()
Dim wsn As String, _
cn As String
'Use a valid CodeName here.
cn = "Data_Vi"
wsn = NameFromCodeName(cn)
MsgBox "Worksheet Name: """ & wsn & """" & Chr(13) & Chr(13) _
& "Entered Code Name: """ & cn & """" _
, vbInformation + vbOKOnly, "Name From CodeName TEST"
'Use a invalid CodeName here.
wsn = NameFromCodeName("I_ERROR")
End Sub 'TEST_NameFromCodeName
'################################# TESTER #################################