我試圖使用replaceline函數來更新Access VBA模塊中的代碼。它不斷出現編譯錯誤。我檢查過,選擇了VBA擴展並將其與我查過的其他示例進行了比較。替換代碼模塊中的文本
這是我第一次使用這種類型的功能,所以我還沒有完全理解他們。
下面
Sub ReplaceCodeModuleText(strModule As String, strFindWhat As String, strReplaceWith As String)
'FUNCTION:
' Search the code module for specific text
' Replace with new text
Dim VBProj As VBProject
Dim VBComp As VBComponent
Dim CodeMod As CodeModule
Dim SL As Long ' start line
Dim EL As Long ' end line
Dim SC As Long ' start column
Dim EC As Long ' end column
Dim strCodeLine As String
Dim vDummy As Variant
Dim Found As Boolean
Set VBProj = Application.VBE.ActiveVBProject
Set VBComp = VBProj.VBComponents(strModule)
Set CodeMod = VBComp.CodeModule ' '.CodeModule
With CodeMod
SL = 1: EL = .CountOfLines
SC = 1: EC = 255
Found = .Find(Target:=strFindWhat, StartLine:=SL, StartColumn:=SC, _
EndLine:=EL, EndColumn:=EC, _
wholeword:=True, MatchCase:=False, patternsearch:=False)
If Found Then
strCodeLine = CodeMod.Lines(SL, 1)
strCodeLine = Replace(strCodeLine, strFindWhat, strReplaceWith, Compare:=vbTextCompare) 'not case sensitive = vbTextCompare
.ReplaceLine(SL, strCodeLine)
Debug.Print "Successfully Replaced: " & strFindWhat & " in VBA Module: " & strModule & " with : " & strReplaceWith
Else
Debug.Print "Did not find: " & strFindWhat;
End If
End With
End Sub
它看起來像你永遠只能處理第一線。 '.Find'行表示從第1行到EL的搜索,但是'strCodeLine'和'.ReplaceLine'的賦值只使用'SL',它看起來沒有被更新。可能值得使用'for'循環,並在模塊的每一行上進行字符串替換和ReplaceLine。 – GregHNZ
@GregHNZ:[CodeModule.Find](https://msdn.microsoft.com/en-us/library/aa443952(v = vs.60).aspx)設置其StartLine,StartColumn等參數。感謝Andre, – Andre