如何在文本中插入逗号?

时间:2013-05-20 08:36:24

标签: csv vbscript

我必须使用VBScript在文本行的某些点插入逗号。我需要它用if语句检查每行的前四个字符,如果匹配,则插入该行所需的逗号,这是我到目前为止所拥有的:

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("H:\Letter Display\Letters\LTRPRT__00000008720000000001NI-K-RMND.txt", ForReading)

strNIK = "1000"
strLine = objFile.ReadLine

If Left(strLine,4) = strNIK then

  arrCommas = Array(16,31,46,56,66,79,94,99)

  Do Until objFile.AtEndOfStream

    intLength = Len(strLine)
    For Each strComma in arrCommas
      strLine = Left(strLine, strComma - 1) + "," + Mid(strLine, strComma, intLength)
    Next
    strText = strText & strLine & vbCrLf
  Loop

end if

objFile.Close

Set objFile = objFSO.OpenTextFile("H:\Letter Display\Letters\LTRPRT__00000008720000000001NI-K-RMND.txt", ForWriting)
objFile.Write strText
objFile.Close

如果有人可以帮助将其作为IF声明,那将非常感激。

1 个答案:

答案 0 :(得分:1)

您需要在ReadLine

内移动Do..Loop和条件
strNIK = "1000"
arrCommas = Array(16,31,46,56,66,79,94,99)

Do Until objFile.AtEndOfStream
  strLine = objFile.ReadLine

  If Left(strLine, 4) = strNIK then
    intLength = Len(strLine)
    For Each strComma in arrCommas
      strLine = Left(strLine, strComma - 1) + "," _
        + Mid(strLine, strComma, intLength)
    Next
  End If

  strText = strText & strLine & vbCrLf
Loop

如果您希望输出仅包含已修改的行,请在条件内移动行strText = strText & strLine & vbCrLf

If Left(strLine, 4) = strNIK then
  '...
  strText = strText & strLine & vbCrLf
End If

数组中的逗号索引是否已经考虑了字符插入引起的位置偏移?

此外,将输出逐行写入临时文件,然后在完成所有输入处理后将输入文件替换为该临时文件可能是个好主意:

Set inFile  = objFSO.OpenTextFile(inputFilename, ForReading)
Set outFile = objFSO.OpenTextFile(outputFilename, ForWriting)

Do Until inFile.AtEndOfStream
  strLine = inFile.ReadLine
  'do stuff with strLine
  outFile.WritLine
Loop

inFile.Close
outFile.Close

objFSO.DeleteFile inputFilename, True
objFSO.MoveFile outputFilename, inputFilename

这样可以避免在处理大文件时耗尽内存。

您可以在给定目录中处理具有特定扩展名的所有文件,如下所示:

folderName = "C:\some\folder"

For Each objFile In objFSO.GetFolder(folderName).Files
  If LCase(objFSO.GetExtensionName(objFile.Name)) = "ltr" Then
    'processing takes place here
  End If
Next

如果你想使用我上面建议的inputfile / outputfile方法,你可以为每个输入文件使用相同的临时输出文件名,或者你可以从输入文件名中派生输出文件名,例如:像这样:

inputFilename  = objFile.Name
outputFilename = inputFilename & ".tmp"