【问题标题】:replace text in code module替换代码模块中的文本
【发布时间】:2017-11-05 02:09:56
【问题描述】:

我正在尝试使用 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 循环并在模块中的每一行上执行字符串替换和替换线。
  • @GregHNZ:CodeModule.Find设置它的StartLine、StartColumn等参数。

标签: ms-access vba vbe


【解决方案1】:
        .ReplaceLine(SL, strCodeLine)

必须是任一

        Call .ReplaceLine(SL, strCodeLine)

        .ReplaceLine SL, strCodeLine

【讨论】:

  • 感谢安德烈,解决了问题。我没有看到任何使用“呼叫”程序的示例。我注意到的一件事是,我需要确保不会在正在使用的函数上调用它,因为它会导致 Access 崩溃(有点道理)。
  • 如果答案解决了您的问题,您可以accept它,这也标志着问题已解决。 @IanCox
猜你喜欢
  • 2017-10-05
  • 2016-03-10
  • 2019-02-07
  • 2012-02-07
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多