2017-06-04 91 views
1

我試圖使用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 
+0

它看起來像你永遠只能處理第一線。 '.Find'行表示從第1行到EL的搜索,但是'strCodeLine'和'.ReplaceLine'的賦值只使用'SL',它看起來沒有被更新。可能值得使用'for'循環,並在模塊的每一行上進行字符串替換和ReplaceLine。 – GregHNZ

+0

@GregHNZ:[CodeModule.Find](https://msdn.microsoft.com/en-us/library/aa443952(v = vs.60).aspx)設置其StartLine,StartColumn等參數。感謝Andre, – Andre

回答

0
 .ReplaceLine(SL, strCodeLine) 

代碼必須是

 Call .ReplaceLine(SL, strCodeLine) 

 .ReplaceLine SL, strCodeLine 
+0

,解決了這個問題。我沒有看到任何使用「調用」過程的例子。我注意到的一件事是,我需要確保我不會調用它正在使用的函數,因爲它會導致Access崩潰(有道理)。 –

+0

如果答案解決了您的問題,您可以[接受](http://stackoverflow.com/help/someone-answers)它,這也標誌着問題已解決。 @IanCox – Andre