VBSでのファイル入出力
VBS(VBスクリプト)が他のVB系との一番の違いは、変数の型がvariantしかなく、ファイル入出力がストリームしかないことだと思います。
つまり、従来のファイルに対してのオープンクローズでなく、ストリームオブジェクトに対してのオープンクローズ操作になるのです。
また、変数はvariantしかないので、型を宣言する必要がなく、関数のリターン値の型も宣言する必要がなのです。
ストリームオブジェクトを使ったファイルコピーのサンプル
WScript.Echo "TEST開始" If TestFileCopy = 0 then WScript.Echo "コピー正常" Else WScript.Echo "コピー異常" End if WScript.Echo "TEST終了" WScript.Quit(0) Function TestFileCopy() '---------------------------------------------------- 'TEST testIn.csv copy to testOut.csv '---------------------------------------------------- const ForReading = 1, ForWriting = 2, ForAppending = 3 Dim strPathIn Dim strPathOut Dim fs, fr, fw Dim intSts strPathIn = "testIn.csv" strPathOut = "testOut.csv" Set fs = CreateObject("Scripting.FileSystemObject") If fs.fileexists(strPathIn) then Set fr = fs.OpenTextFile(strPathIn, ForReading) Set fw = fs.OpenTextFile(strPathOut, ForWriting,True) Do While Not fr.AtEndOfStream fw.WriteLine fr.ReadLine Loop fw.Close fr.Close Set fw = Nothing Set fr = Nothing intSts = 0 Else Call MsgBox("ファイル見つからない!",48,"エラー") intSts = 1 End if Set fs = Nothing TestFileCopy = intSts End Function
尚、OpenTextFileの第3引数は、省略可能で、Trueを指定した場合は、ファイルがなければ新規に作成するという指定になります。