【问题标题】:VBA: Replace text from txt for each line and save asVBA:为每一行替换txt中的文本并另存为
【发布时间】:2016-12-30 18:24:21
【问题描述】:

有人可以帮我解决以下问题吗?我尝试自己制作,但我所能做的就是打开一个 txt 并用静态词替换静态词。

VBA 脚本:

打开并阅读 ThisVbaPath.WordsToUse.txt 的第一行

在ThisVbaPath.BaseDoc.docx(或txt)中打开并查找USER_INPUT

将所有出现的 USER_INPUT 替换为 WordsToUse.txt 中的第一行

将 BaseDoc.docx 保存为 BaseDoc&First_Line.docx

全部关闭

下一行做同样的事情,但不要要求用户输入,使用前一个

如果出错则下一步

完成后显示是否有任何错误(我猜不太可能)

我会每周使用它来处理 150 行左右。

谢谢!

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出......到目前为止你写过任何代码

标签: vba excel flat-file


【解决方案1】:
Sub TextFile_FindReplace()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

FilePath = Application.ActiveWorkbook.Path & "\NEWTEST.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)


FileContent = Replace(FileContent, "FOO", "BAR")


Print #TextFile, FileContent
Close TextFile
End Sub

【讨论】:

    【解决方案2】:

    我认为这样的事情应该可行吗?

    Sub test()
    
      Dim text, textReplace, findMe As String
    
      findMe = InputBox("What Text To Find?")
      Open "C:\Excel Scripts\test.txt" For Input As #1
      Open "C:\Excel Scripts\test2.txt" For Input As #2
      Open "C:\Excel Scripts\output.txt" For Output As #3
    
      While Not EOF(1)
        Line Input #1, text
          While Not EOF(2)
            Line Input #2, textReplace
            Write #3, Replace(text, findMe, textReplace)
          Wend
      Wend
    
      Close #1
      Close #2
      Close #3
    
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2018-11-14
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多