Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one solution:

Sub tester()
    Dim WBA As Workbook

    Set WBA = Workbooks("Book1")
    WorksheetByCodeName(WBA, "codeNameHere").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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...