1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VBAのファイル操作

Last updated at Posted at 2021-12-16

約20年ぶりにVBAのファイル操作のマクロを組んだので忘備録として投稿

実装

参照設定で「Microsoft Scripting Runtime」を追加
スクリーンショット 2021-12-16 091745.png

サンプルコード

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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?