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

时间:2019-02-25 13:35:19

标签: excel vba text replace

我在VBA方面的经验几乎为零,所以请在这里忍受。

我正在尝试创建一个宏,该宏打开文本文件并在Excel的单元格A1中找到该文本,并将其替换为单元格B1中的文本。然后,它应该找到位于单元格A2中的文本,并将其替换为单元格B2,依此类推,直到A列中最后一个包含数据的单元格。

现在,我搜索了一下,偶然发现了这个工作代码:

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

除1个小问题外,它的工作与预期完全相同。似乎复制了文本文件中的最后几个字符,并将其追加到最后一个字符之后,进行了一些重复。

示例:

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

运行代码之前:

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

运行代码后:

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

最后几个字符“ om text”被复制并按原样输出。有时,根据文件大小,可能会复制更多字符。我该如何解决?

1 个答案:

答案 0 :(得分:2)

当输出字符串短于输入字符串时,可能会发生这种情况。您正在打开文件以进行读写,读取文本(假设为100字节),进行替换(假设为90字节)。然后,在开始处写入90个字节。文件中剩余的10个字节保持不变。

您应该首先打开文件以进行读取(然后将其关闭),然后再打开以将文本写入其中-打开文件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
相关问题