オフィス・ブール ロゴ
【レスキュー連絡先】
代表 : 末永 尚登
TEL: 070-4087-0025 FAX:095-893-6090

【 VBAパーツ 】

5.CSVデータの入力と出力

CSVファイルの読み書きの基本です。Line Input、Print命令で入出力を記述します。

Public Sub ReadCSV()
'CSVファイルの読み込み

    Dim n As Long
    Dim myFields As Variant
    Dim inRec As String
    Dim r As Long
    Dim c As Long
    

    n = FreeFile
    Open ThisWorkbook.Path & "\test.csv" For Input As #n
    r = 1
    Do While Not EOF(n)
        Line Input #n, inRec
        myFields = Split(inRec, ",")
        For c = 0 To UBound(myFields)
            Cells(r, c + 1).Value = myFields(c)
        Next c
        r = r + 1
    Loop
    Close #n
    
End Sub
Public Sub WriteCSV()
'CSVファイルの出力

    Dim n As Long
    Dim outRec As String
    Dim r As Long
    Dim c As Long
    
    
    n = FreeFile
    Open ThisWorkbook.Path & "\test.csv" For Output As #n
    For r = 1 To 5
        outRec = Cells(r, 1).Value
        For c = 2 To 5
            outRec = outRec & "," & Cells(r, c).Value
        Next c
        Print #n, outRec
    Next r
    Close #n
    
End Sub
Public Sub AddCSV()
'CSVファイルへの追記

    Dim n As Long
    Dim outRec As String
    Dim r As Long
    Dim c As Long
    
    
    n = FreeFile
    Open ThisWorkbook.Path & "\test.csv" For Append As #n
    For r = 1 To 5
        outRec = Cells(r, 1).Value
        For c = 2 To 5
            outRec = outRec & "," & Cells(r, c).Value
        Next c
        Print #n, outRec
    Next r
    Close #n
    
End Sub


 


オフィス・ブール ロゴ 所在地:長崎県長崎市  代表:末永尚登
E-mail: suenaga@officeboole.com   TEL: 070-4087-0025  FAX: 095-893-6090