約20年ぶりにVBAのファイル操作のマクロを組んだので忘備録として投稿
- 当時はOpenステートメント を使っていたが、今回はFileSystemObjectを使用。
実装
参照設定で「Microsoft Scripting Runtime」を追加
サンプルコード
Modlue1.bas
Public Function FSOInputOutput(inputFilePath As String, outputFilePath) As Boolean
On Error GoTo ErrHandler
Dim resultFlg As Boolean: resultFlg = False
Dim FSO As FileSystemObject
Dim inputReader As TextStream
Dim outputWriter As TextStream
Dim strLine As String
Dim strArray_I As Variant
Dim tempStr As String
Set FSO = New FileSystemObject
'出力ファイルが存在しない場合はエラー
If FSO.FileExists(inputFilePath) = False Then
GoTo ErrHandler
End If
'入出力ファイルのオブジェクト取得
Set inputReader = FSO.OpenTextFile(inputFilePath, ForReading, False, TristateFalse)
Set outputWriter = FSO.OpenTextFile(outputFilePath, ForWriting, True, TristateFalse)
Do Until inputReader.AtEndOfStream
strLine = inputReader.ReadLine
strArray_I = Split(strLine, ",")
'=== 編集 ===
tempStr = strArray_I(0) & Int(100 * Rnd + 1) & "," & strArray_I(1) & Int(100 * Rnd + 1)
outputWriter.WriteLine tempStr
Loop
outputWriter.Close
inputReader.Close
resultFlg = True
ErrHandler:
Set outputWriter = Nothing
Set inputReader = Nothing
Set FSO = Nothing
FSOInputOutput = resultFlg
End Function
ThisWorkbook
Private Sub Workbook_Open()
Const INPUT_FILE_PATH = "C:\temp\sample.csv"
Const OUTPUT_FILE_PATH = "C:\temp\sample_result.csv"
Dim resultFlg As Boolean
resultFlg = Module1.FSOInputOutput(INPUT_FILE_PATH, OUTPUT_FILE_PATH)
If resultFlg = True Then
MsgBox "成功", vbInformation + vbOKOnly
Else
MsgBox "失敗", vbCritical + vbOKOnly
End If
End Sub