简体   繁体   English

Excel VBA在.txt文件中查找/替换文本

[英]Excel VBA find/replace text in .txt file

I have near zero experience with VBA so bear with me here. 我在VBA上的经验几乎为零,请在这里与我保持联系。

I'm trying to create a macro that open a text file and find the text located in Excel's cell A1, and to replace it with text in cell B1. 我正在尝试创建一个宏,该宏打开一个文本文件并找到位于Excel单元格A1中的文本,并将其替换为单元格B1中的文本。 Then, it should find the text located in cell A2, and replace it with cell B2, and so on until the last cell in column A that contains data. 然后,它应该找到位于单元格A2中的文本,并将其替换为单元格B2,依此类推,直到列A中包含数据的最后一个单元格为止。

Now, I've searched a bit and stumbled upon this working code: 现在,我搜索了一下,偶然发现了这个工作代码:

Sub Replace_Text()
Dim strFile As String
Dim i As Integer
Dim strText As String
Dim cell As Range
With Application.FileDialog(msoFileDialogFilePicker)
    .InitialFileName = ThisWorkbook.Path
    If .Show <> -1 Then Exit Sub
    strFile = .SelectedItems(1)
End With
i = FreeFile
strText = Space(FileLen(strFile))
With CreateObject("vbscript.regexp")
    .Global = True
    Open strFile For Binary Access Read Write As #i
        Get #i, , strText
        For Each cell In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
            .Pattern = Replace(Replace(Replace(Replace(cell.Value, "?", "\?"), "*", "\*"), "+", "\+"), ".", "\.")
            strText = .Replace(strText, cell.Offset(, 1).Value)
        Next cell
        Put #i, 1, strText
    Close #i
End With     
End Sub

It's working exactly as intended, except for 1 minor problem. 它完全按预期工作,除了1个小问题。 It seems to copy the last few characters in the text file and append it after the last character, making some duplication. 似乎复制了文本文件中的最后几个字符,并将其附加在最后一个字符之后,从而产生了一些重复。

Example: 例:

Column A | Column B
<Var1>   | Patrick
<Var2>   | ghosts

Before running code: 在运行代码之前:

This is <Var1>.
There are <Var2>.
Some random text

After running code: 运行代码后:

This is Patrick.
There are ghosts.
Some random textom text

The last few characters "om text" got duplicated and output as such. 最后几个字符“ om text”被复制并按原样输出。 Sometimes more characters got duplicated depending on the file size. 有时,更多的字符被复制,具体取决于文件的大小。 How do I fix this? 我该如何解决?

Probably, this happens when the output string is shorter than the input. 当输出字符串短于输入字符串时,可能会发生这种情况。 You are opening the file for read and write, read the text (let's say 100 bytes), do your replaces (let's say 90 bytes). 您正在打开文件以进行读写,读取文本(假设为100字节),进行替换(假设为90字节)。 Then you write the 90 bytes at the beginning. 然后,在开始处写入90个字节。 The remaining 10 bytes in the file stay untouched. 文件中的其余10个字节保持不变。

You should open the file first just for read (and close it), then open it again to write the text into it - the old content will be thrown away when you open the file for Output 您应该首先打开文件以进行读取(然后关闭),然后再次打开以将文本写入其中-打开文件for Output时,旧内容将被丢弃for Output

    Open strFile For Binary Access Read Write As #i
    Get #i, , strText
    Close #i

    For Each cell In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
       ...
    Next cell

    Open strFile For Output As #i
    Write #i, strText
    Close #i

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

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