kurukuru-papaのブログ

主に、ソフトウェア開発に関連したメモを書き溜めたいと思います。

CSV出力

アクティブシートの内容をCSV出力するマクロを作成しました。出力ファイルは、元のExcelファイルのファイル名に".csv"を付加した名前になります。

Public Sub CSV出力()
    Dim fname As String
    Dim lastCell As Range
    Dim cell As Range
    Dim filenum As Integer
    Dim row As Integer
    Dim column As Integer
    Dim line As String

    ' 出力先ファイル名を決定する
    fname = ActiveWorkbook.FullName + ".csv"
    
    ' ファイルを開く
    filenum = FreeFile
    Open fname For Output As #filenum
    
    ' 最終行の取得
    ' 誤認識する場合あり
    Set lastCell = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell)

    ' 行と列でループしながらデータ書き込み
    For row = 1 To lastCell.row
        line = ""
        For column = 1 To lastCell.column
            Set cell = Cells(row, column)
            If column > 1 Then
                line = line + ","
            End If
            line = line + cell.Value
        Next
        Print #filenum, line
    Next
    
    ' ファイルを閉じる
    Close #filenum
    
    MsgBox fname + "を出力しました。"
End Sub