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?
RegExand just useVBA - Replace?