.csv文件的正確工具是ADO。您需要通過將列添加到現有表來創建新的(文本)表是SQL語句,如下所示:
SELECT S. *,'whatever'&(IIF([B] ='J',' - J」, '-n'))作爲[NEWCOL] INTO [dst.csv] FROM [src.csv] S
以及 - 在一般 - 一個schema.ini文件等
[src.csv]
ColNameHeader=True
Format=Delimited(;)
Col1=A Integer
Col2=B Char Width 15
[dst.csv]
ColNameHeader=True
Format=Delimited(;)
Col1=A Integer
Col2=B Char Width 15
Col3=NewCol Char Width 15
指定你的桌子結構明確。
在代碼:
' Absolute path to .CSV folder
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sDS : sDS = oFS.GetAbsolutePathName("..\Data\txt")
' Connectionstring
Dim sCS : sCS = Join(Array(_
"Provider=Microsoft.Jet.OLEDB.4.0" _
, "Data Source=" & sDS _
, "Extended Properties=""" & Join(Array(_
"Text" _
, "HDR=Yes" _
), ";") & """" _
), ";")
' Database/Connection
Dim oDb : Set oDb = CreateObject("ADODB.Connection")
Dim sSQL
oDb.Open sCS
' show src
sSQL = "SELECT * FROM [src.csv]"
WScript.Echo sSQL
WScript.Echo oDb.Execute(sSQL).GetString(adClipString, , vbTab, vbCrLf, "null")
' copy/append col to new dst
If oFS.FileExists(oFS.BuildPath(sDS, "dst.csv")) Then oFS.DeleteFile oFS.BuildPath(sDS, "dst.csv")
sSQL = "SELECT S.*, 'whatever' & (IIF([B]='J','-j', '-n')) As [NewCol] INTO [dst.csv] FROM [src.csv] S"
WScript.Echo "--------------"
WScript.Echo "Exec:", sSQL
oDb.Execute sSQL
' show dst
sSQL = "SELECT * FROM [dst.csv]"
WScript.Echo "--------------"
WScript.Echo sSQL
WScript.Echo oDb.Execute(sSQL).GetString(adClipString, , vbTab, vbCrLf, "null")
輸出:
SELECT * FROM [src.csv]
1 J
2 N
3 J
4 N
--------------
Exec: SELECT S.*, 'whatever' & (IIF([B]='J','-j', '-n')) As [NewCol] INTO [dst.csv] FROM [src.csv] S
--------------
SELECT * FROM [dst.csv]
1 J whatever-j
2 N whatever-n
3 J whatever-j
4 N whatever-n
這樣你減少失誤像
- 污染與未使用(UND你的代碼的風險未使用)變量(rowcounter)
- 試圖從數組中拆分一個元素通過分在同一個分離器
- 訪問由.ReadLine(下一/錯線)兩次
零