0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excel VBAでCSV出力を行う

Posted at

概要

ExcelVBAからCSV出力をする際の備忘録

目的

CSVの情報を利用したいけどメモ帳のデータを一つずつ修正するのは骨が折れます。
そんな時はExcelで情報を一括作成、出力を行うことで楽になります。
ここではExcelシート上で作成した情報を、CSVファイルとして出力する方法を記載します。

実装

出力処理を関数化し、作ってみます。

Public Sub exportCsv(outputPath As String)
    Dim outputPath As String: outputPath = "D:\local\desktop\test2.csv"
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' 以下Shift-JIS用、ASCIIを読み込む場合は第三引数に[True]を設定する。
    Dim ts As Object: Set ts = fso.CreateTextFile(outputPath, True, False)

    Dim r As Long, c As Long
    Dim lastRow As Long, lastCol As Long
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    For r = 1 To lastRow
        Dim line As String
        line = ""

        For c = 1 To lastCol
            Dim v As String
            v = ws.Cells(r, c).Text

            line = line & v
            If c < lastCol Then line = line & ","
        Next c

        ts.WriteLine line
    Next r

    ts.Close
End Sub

引数で出力先ファイルを指定しています。
上記関数は以下のように使用できます。

Public Sub main2()
    
    Dim FileName As String
    FileName = Application.GetSaveAsFilename(InitialFileName:="data.csv", FileFilter:="csvファイル,*.csv")
    If FileName = "" Then
        Exit Sub
    End If
    
    Call exportCsv(FileName)
    
End Sub

最後に

これを使えば簡単、高速でCSVを作成、運用できます。
テストデータ作成などで重宝します。
ぜひ色々試してみてください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?