LoginSignup
2
1

More than 1 year has passed since last update.

エクセルデータをダブルクォーテーション囲み、改行コードLFでCSV化する方法

Last updated at Posted at 2023-06-21

やりたいこと

エクセルで管理しているデータのリストをダブルクォーテーション(")区切りでCSV化する。

使い方

以下コード実行でエクセルが保存されているディレクトリにCSVが生成される。
シート名がファイル名になり、複数シートある場合は複数ファイル作成される。

ソース(VBA)

ThisWorkbook
Public Sub MainProc()
    Dim shtData As Worksheet
    Dim filePath As String
    Dim lastRow As Long
    Dim lastCol As Long
    Dim varData As Variant
    Dim i As Long
    Dim j As Integer
    Dim line As String
    Dim colString As String
    
    ' 全シートを 1 つずつループ
    For Each objSheet In ThisWorkbook.Worksheets
        '「データ」シートを変数に格納する
        Set shtData = objSheet
                
        'CSVファイルパスを変数に格納する
        filePath = ThisWorkbook.Path & "\" & shtData.Name & ".csv"
        
        '「データ」シートの最終行を取得する
        lastRow = shtData.Cells(shtData.Rows.Count, 1).End(xlUp).Row
            
        '「データ」シートの最終列を取得する
        lastCol = shtData.Cells(1, shtData.Columns.Count).End(xlToLeft).Column
            
        '「データ」シートに入力されているデータを配列に格納する
        varData = shtData.Range(shtData.Cells(1, 1), shtData.Cells(lastRow, lastCol))
        
        '⑦作成するファイルを開く
        Open filePath For Output As #1
        
        'ダブルコーテーションくくりのデータを書き込みする
        For i = 1 To lastRow
            line = ""
            
            ' 先頭行はスキップ
            If i = 1 Then
                GoTo Continue:
            End If
            
            For j = 1 To lastCol
                
                ' エスケープ処理
                colString = varData(i, j)
                colString = Replace(colString, vbLf, "\n")
                colString = Replace(colString, """", """""")
                
                ' ダブルクォーテーションで囲む
                colString = """" & colString & """"
                
                line = line & colString
                
                If j <> lastCol Then
                    line = line & ","
                End If
                
            Next
            
            Print #1, line & vbLf
    Continue:
        Next i
        
        '作成するファイルを閉じる
        Close #1
    Next
    
    MsgBox "完了"
End Sub

2
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
2
1