搜索特定文本的代码然后删除它并用另一个单词替换它

时间:2014-02-14 03:15:18

标签: excel excel-vba vba

我有代码删除vba项目代码中的某个单词并将其替换为另一个单词。我似乎无法让它发挥作用。谁能告诉我我做错了什么?

Private Sub CommandButton3_Click()

Dim myBook As Object
Dim i As Long
Dim j As Long
Dim strToReplaceWith As String, strToReplace As String, Replacing As String, Replaced As               
String

n = Range("L10").Value
Replacing = "Data_Acq_1Gal"
Replaced = "Data_Acq_1Gal " & "(" & n & ")"
Set myBook = ActiveWorkbook.VBProject
For Each myBook In Application.Workbooks
For i = 1 To myBook.VBProject.VBComponents.Count
For j = 1 To 34
If InStr(1, myBook.VBProject.VBComponents(i).CodeModule.Lines(j, 1), Replacing, vbTextCompare) Then       
myBook.VBProject.VBComponents(i).CodeModule.DeleteLines j
strToReplace = myBook.CodePanes.Item(i).CodeModule.Lines(j, 1)
strToReplaceWith = Replace(strToReplace, Replacing, Replaced, 1, 1, vbTextCompare)
myBook.VBProject.VBComponents(i).CodeModule.InsertLines j, strToReplaceWith
End If
Next j
Next i
Next myBook

End Sub

1 个答案:

答案 0 :(得分:0)

您的代码中的一个主要缺陷是,如果它成功运行,那么它也会覆盖模块中的搜索字符串。为确保不会这样做,我们将使用预定义字符串填充搜索字符串。我使用#$%@作为填充。

这是你在尝试的吗?

'~~> We need so that the code doesn't replace the search string in itself
Const sPad As String = "#$%@"

Sub Sample()
    Dim wb As Workbook
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim CodeMod As VBIDE.CodeModule
    Dim WordToReplace As String, NewWord As String
    Dim ActualSearchWord As String, NewString As String
    Dim i As Long, j As Long

    '~~> Change this to the relevant sheet
    n = ThisWorkbook.Sheets("Sheet1").Range("L10").Value

    '~~> Padding our search string
    WordToReplace = sPad & "Data_Acq_1Gal ()" & sPad
    ActualSearchWord = Replace(WordToReplace, sPad, "")
    NewWord = "Data_Acq_1Gal " & "(" & n & ")"

    For Each wb In Workbooks
        '~~> Remove the below IF/ENDIF if you want the code to replace 
        '~~> in other modules of this workbook
        If wb.Name <> ThisWorkbook.Name Then 
            Set VBProj = wb.VBProject

            For Each VBComp In VBProj.VBComponents
                Set CodeMod = VBComp.CodeModule
                With CodeMod
                    j = .CountOfLines

                    For i = 1 To j
                        If InStr(1, .Lines(i, 1), ActualSearchWord, vbTextCompare) > 0 And _
                        InStr(1, .Lines(i, 1), WordToReplace, vbTextCompare) = 0 Then
                            NewString = Replace( _
                                                 .Lines(i, 1), _
                                                 ActualSearchWord, _
                                                 NewWord, 1, , vbTextCompare)
                            .ReplaceLine i, NewString
                        End If
                    Next i
                End With
            Next VBComp
        End If
    Next
End Sub