0

I have a worksheet and worksheet related code called "GL Budget2". The code contains several instances of the string "GL Budget". This string must be renamed "GL Budget2" by using code from within another macro called FindAndReplace. My code (thanks to Pearson):

Sub FindAndReplace()

    Dim SL As Long, EL As Long, SC As Long, EC As Long
    Dim S As String
    Dim Found As Boolean

    With ThisWorkbook.VBProject.VBComponents("GL Budget2").CodeModule
        SL = 1
        SC = 1
        EL = 99999
        EC = 999
        Found = .Find("GL Budget", SL, SC, EL, EC, True, False, False)

        If Found = True Then
            S = .Lines(SL, 1)
            S = Replace(S, "GL Budget", "GL Budget2")
            .ReplaceLine SL, S
        End If

    End With
End Sub

It crashes with the subscript out of range error on the line

With ThisWorkbook.VBProject.VBComponents("GL Budget2").CodeModule

Any suggestions would be greatly appreciated.

1 Answer 1

1

GL Budget2 is likely not the code name of your sheet, but the name on the sheet tab.

Try this:

Dim cn as string

cn = ThisWorkbook.Sheets("GL Budget2").CodeName

With ThisWorkbook.VBProject.VBComponents(cn).CodeModule
'...etc
Sign up to request clarification or add additional context in comments.

3 Comments

Tim: GL Budget is the name of the original tab, and GL Budget2 is the name of the copy. GL Budget has event handler code that is exactly copied for GL Budget2, but I need to change the sheet name within the GL Budget2 code from "GL Budget" to "GL Budget2" in order for the code to point to the correct sheet and work correctly. When I insert your code, the error goes away, but the string substitution does not happen.
Do you have the sheet name hard-coded in its code module? You could use Me.Name to replace that.
Tim, your suggestion was in the ballpark and now it works, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.