使用另一个宏中的代码在工作表宏中查找和替换字符串

时间:2015-02-24 23:41:39

标签: vba excel-vba excel

我有一个名为" GL Budget2"的工作表和工作表相关代码。该代码包含字符串" GL Budget"的几个实例。必须重命名此字符串" GL Budget2"通过使用另一个名为FindAndReplace的宏中的代码。我的代码(感谢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

它崩溃了行

上的下标超出范围错误
With ThisWorkbook.VBProject.VBComponents("GL Budget2").CodeModule

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

GL Budget2可能不是工作表的代码名称,而是工作表标签上的名称。

试试这个:

Dim cn as string

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

With ThisWorkbook.VBProject.VBComponents(cn).CodeModule
'...etc