简体   繁体   中英

Excel VBA find/replace text in .txt file

I have near zero experience with VBA so bear with me here.

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. 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.

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. 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. 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). Then you write the 90 bytes at the beginning. The remaining 10 bytes in the file stay untouched.

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

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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