我需要用Excel中特定列中的字符串修改文本文件。当我执行代码时,我发现一些值是重复的。它似乎与旧值结尾的数字有关,后者以某种方式被解释为副本。但是,这种情况并非每次都会发生,我感到很困惑。有10,000个条目需要更改,但是我创建的小测试文件显示了一个更大的问题。 Test Files希望此链接能够正常工作,如果能找到我的测试文件Test.txt,TestBook.xlsm和Test-L5K.txt,其中包含要修改的实际文件的一部分。
谢谢。
random_state=42
答案 0 :(得分:0)
编辑:重探了asfter并查看了您的源文件-我对这些文件做出了一些错误的假设...
注意::您的某些搜索字词是其他搜索字词的子字符串,因此您将需要按字词长度降序对映射表进行排序,否则最终将替换较短的部分长期。
例如:
N21:370/08 Prep_Peel_Peeler1DisconnectSwitchAlarm
N21:370/02 Prep_Peel_Peeler2DisconnectSwitchAlarm
N21:370/0 Prep_Peel_HalvingUnitMotorDisconnectAlarm
如果您将N21:370/0替换为前两个,那将无法获得预期的结果。
Private Sub CommandButton21_Click()
Dim sBuffer As String, sFileName As String
Dim sFileNameOut As String
Dim rngLookup As Range, m
Dim iFileNumIn As Integer, iFileNumOut As Integer
Dim arrMap, i As Long, numReplacements As Long
'sFileName = Application.GetSaveAsFilename() 'Path to target file
sFileName = "C:\_Stuff\test\Test - L5K.txt"
iFileNumIn = FreeFile
Open sFileName For Input As iFileNumIn
sFileNameOut = Replace(sFileName, ".txt", "_mod.txt")
iFileNumOut = FreeFile
Open sFileNameOut For Output As iFileNumOut
With Sheets("Sheet1")
Set rngLookup = .Range(.Range("D2"), .Cells(.Rows.Count, "E").End(xlUp))
arrMap = rngLookup.Value
End With
'Perform replacements
Do While Not EOF(iFileNumIn)
Line Input #iFileNumIn, sBuffer
If Len(sBuffer) > 0 Then
For i = 1 To UBound(arrMap)
If InStr(sBuffer, arrMap(i, 1)) > 0 Then
sBuffer = Replace(sBuffer, arrMap(i, 1), arrMap(i, 2))
If numReplacements <= 10 Then Debug.Print arrMap(i, 1), ">>", arrMap(i, 2)
numReplacements = numReplacements + 1
End If
Next i
End If
Print #iFileNumOut, sBuffer
Loop
Close iFileNumIn
Close iFileNumOut
Debug.Print "Made " & numReplacements & " replacements"
End Sub