[英]Excel VBA find/replace text in .txt file
我在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”被復制並按原樣輸出。 有時,更多的字符被復制,具體取決於文件的大小。 我該如何解決?
當輸出字符串短於輸入字符串時,可能會發生這種情況。 您正在打開文件以進行讀寫,讀取文本(假設為100字節),進行替換(假設為90字節)。 然后,在開始處寫入90個字節。 文件中的其余10個字節保持不變。
您應該首先打開文件以進行讀取(然后關閉),然后再次打開以將文本寫入其中-打開文件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.