How can I get worksheet code name to activate a specific worksheet?

六眼飞鱼酱① 提交于 2019-12-20 05:49:10

问题


I have a worksheet with the "tab" name of "Rpt_Group". I also renamed its code name to shData. When I use VBA to activate the worksheet using "Rpt_Group" it runs fine. But when I use the code name I get an error message

"subscript out of range.

This works: WBA.Worksheets("Rpt_Group").Activate

This does not work: WBA.Worksheets("shData").Activate

This does not work: WBA.shData.Activate

Dim WBA As Workbook

'Open the desired workbook
Set WBA = Workbooks.Open(Filename:="path & file name")

'Activate the desired worksheet
WBA.Worksheets("Rpt_Group").Activate 'this works

This does not work: WBA.Worksheets("shData").Activate

This does not work: WBA.shData.Activate


回答1:


Here's one solution:

Sub tester()
    Dim WBA As Workbook

    Set WBA = Workbooks("Book1")
    WorksheetByCodeName(WBA, "Sheet3").Activate

End Sub

'Get a worksheet with matching codeName (or Nothing if no match)
'    from a workbook wb
Function WorksheetByCodeName(wb As Workbook, codeName As String)
    Dim ws As Worksheet, rv As Worksheet
    For Each ws In wb.Worksheets
        If ws.codeName = codeName Then
            Set rv = ws
            Exit For
        End If
    Next ws
    Set WorksheetByCodeName = rv
End Function

Probably want to check the return value before trying to do anything with it.



来源:https://stackoverflow.com/questions/58549008/how-can-i-get-worksheet-code-name-to-activate-a-specific-worksheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!