Reading a CSV file using VBScript

旧时模样 提交于 2019-12-17 20:29:42

问题


I have a file with 4 fields.

A,B,C,D

I want to only extract the 4th Field and change it to "E"

Is there anyway to accomplish this?


回答1:


Assuming that the values don't contain commas, read in the file using FileSystemObject (FSO), then Split each line on commas. Change the resulting array of 4 values as needed, then join it together as a comma separated string again. When you've done all the changes, write the data back out to a file using FSO.

So something like:

Set outputFile = fso.OpenTextFile(FileName1, ForWriting, True)
Set inputFile = fso.OpenTextFile(FileName2, ForReading)
Do While inputFile.AtEndOfStream <> True
    arr = Split(inputFile.ReadLine, ",")
    arr(3) = "E"
    outputString = Join(arr, ",")
    outputFile.WriteLine outputString
Loop

Please note, the code is completely untested and written mostly from memory so is almost certainly not correct but just to give you an idea.




回答2:


Maybe a simple Replace would work.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\data.txt")
strSearchString = objFile.ReadAll
objFile.Close

strSearchString = Replace(strSearchString,"A,B,C,D","A,B,C,E")

Set objFile = objFSO.OpenTextFile("c:\data.txt",2)
objFile.Write strSearchString
objFile.Close


来源:https://stackoverflow.com/questions/7093550/reading-a-csv-file-using-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!