繁体   English   中英

在 VBA 中使用制表符和换行符查找和替换文本

[英]Find and Replace text with tabs and line breaks in VBA

作为编码的初学者,我正在尝试使用 VBA 替换我的 Python 脚本中的部分代码。 我面临的挑战是我需要用任何内容替换 2 行代码,而 VBA 根本无法在代码中“找到”这两行,我认为这是因为 python 脚本中的空格、制表符. 以下是我尝试过的代码:

尝试 1

strContents = Replace(strContents, "if time == 12:" & vbNewLine & vbTab & "Freq = 1", "") ***' THIS IS THE MOST CRUCIAL LINE - WHICH IS FAILING RIGHT NOW*** 
             


  

我没有添加查找和替换代码的 rest,因为它可以无缝工作,问题在于能够找到这个特定的表达式。

我试图删除(或不替换)的 python 脚本如下所示:

            if time == 12:
                Freq = 1
            else:
                Freq = 12

在另一次尝试中,我还尝试计算空格数,并要求 VBA 查找 python 脚本中的文本以及我可以在脚本中计算的空格数。

我可能遗漏了一些非常基本的东西 - 所以请随时提供您的意见。 您的帮助将不胜感激!

提前谢谢了。 :)

感谢@Aldert 的回复,这是完整的代码:

 Sub FindReplaceTrials()

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim path As String
Dim fileSpec As String
Dim filename As String

path = Application.ActiveWorkbook.path

For m = 4 To 11 ' we need to make this dynamic too
    filename = Worksheets("ScriptName").Cells(m, 1).Value
    fileSpec = path & "\" & filename & ".py"
    'MsgBox (vbCrLf & vbTab & "else:")
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
    If Worksheets(4).Range("B" & 7).Value = 1 Then
        If filename = "econ" Then
            strContents = objTS.ReadAll
            strContents = Replace(strContents, "if time == 12:" & vbCrLf & Space(20) & "freq = 1" & vbCrLf & Space(16) & "else:" & vbCrLf & Space(20) & "freq = 12", "freq = 12")
        Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
        objTS.Write strContents
        objTS.Close
            End If
    End If
    objTS.Close
    Next

End Sub

vbCrLf 和 Space() 对象用于在脚本中找到正确的句子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM