我需要在CSV文件中的多个字符串中替换一些文本,所以我要做的是,使用FileSystemObject(设置对Microsoft Scripting Runtime的引用)将原始文件作为TextStream打开。 我还创建了一个新的空文本文件。 现在,我浏览原始文件,并将每行的副本写到我的新文本文件中。 如果我要搜索的字符串出现在一行中,则将更正后的新文本行写入我的新文本文件中。
继续转到文本文件的末尾。 完成后,保存新的文本文件,删除原始文件,然后将新文件重命名为旧文件名。 (我没有
为了解释下面的示例代码,我正在搜索一个特定的字符串(在这种情况下,我正在寻找这样的行:
,, R01,222,14876.56 ,,,,,
我想在第5个字段中添加美元符号(14876.56)
Dim FSO As Scripting.FileSystemObject
Dim tsFix As Scripting.TextStream
Dim tsOrig As Scripting.TextStream
Dim str_TextLine As String
Dim str_TempFile As String
Dim as_Items() As String
Dim str_OutgoingText As String
Dim lng_ItemNum As Long
Set FSO = New Scripting.FileSystemObject
If FSO.FileExists(str_SavedCSVFileName) Then
' open a new (temp) file
str_TempFile = "TMP_" & str_SavedCSVFileName
Set tsFix = FSO.CreateTextFile(str_TempFile, True)
' open original CSV file
Set tsOrig = FSO.OpenTextFile(str_SavedCSVFileName)
Do Until tsOrig.AtEndOfStream
str_TextLine = tsOrig.ReadLine
If Len(str_TextLine) > 2 And Len(str_TextLine) < 40 Then
' should be a Totals line as below:
' find 4th comma
as_Items = Split(str_TextLine, ",")
For lng_ItemNum = LBound(as_Items) To UBound(as_Items)
' when we find the 4th comma, if the next char is a number, we'll add a $ in front of it
If lng_ItemNum = 4 And IsNumeric(as_Items(lng_ItemNum)) Then
' this should be a dollar value
If InStr(as_Items(lng_ItemNum), ".") Then
str_OutgoingText = Replace(str_TextLine, as_Items(lng_ItemNum), "$" & as_Items(lng_ItemNum)) End If
End If
DoEvents
Next
' write out contents of original CSV file but replace line above with one containing $
tsFix.WriteLine Replace(str_TextLine, as_Items(lng_ItemNum), "$" & as_Items(lng_ItemNum))
Else
' write out contents of original CSV file as is
tsFix.WriteLine str_TextLine
End If
DoEvents
Loop
End If
tsOrig.Close
Set tsOrig = Nothing
tsFix.Close
Set tsFix = Nothing
If FSO.FileExists(str_TempFile) Then
FSO.CopyFile str_TempFile, str_SavedCSVFileName, True
End If
From: https://bytes.com/topic/visual-basic/insights/929013-replacing-text-text-file