在Excel文件的宏中查找/替换字符串

时间:2017-10-02 13:43:59

标签: excel vba excel-vba

因此,我必须浏览几个excel文件,并使用VBA代码以及任何数据连接查找/替换字符串。连接的循环很简单,但我不知道在实际的宏文件本身中是否有快速的方法。如果我需要手动执行此操作,那很好,但我希望有一种灵活的方式。想法?

1 个答案:

答案 0 :(得分:0)

所以在@ Absinthe的文章的帮助下,我能够废弃一些代码来回答我的问题。

Public Sub MacroStringReplace()
    Dim x As Variant, SL As Long, EL As Long, SC As Long, EC As Long
    Dim OLD_STRING As String, NEW_STRING As String, foundString As String

    OLD_STRING = "Old"
    NEW_STRING = "New"

    With Workbooks.Open("C:\docs\foo.xlsm")
        'Macro Server String Replace
        For Each x In .VBProject.VBComponents
            SL = 1: EL = 1: SC = 1: EC = 1                'Default end line and column is 1
            'The find function here returns Boolean
            'SL will be the line number where the string was found (if at all)
            Do Until x.CodeModule.Find(OLD_STRING, SL, EL, SC, EC) = False
                foundString = x.CodeModule.Lines(SL, 1)   'Get the full line of code
                x.CodeModule.ReplaceLine SL, Replace(foundString, OLD_STRING, NEW_STRING)
                SL = 1: EL = 1: SC = 1: EC = 1            'Reset the search numbers
            Loop
        Next
    End With
End Sub

我希望将来对其他人有所帮助。