ホーム 暮らし The Complete Guide to CSV Output with Double Quotes (Includes Copy-Paste Code)

The Complete Guide to CSV Output with Double Quotes (Includes Copy-Paste Code)

篠原 沙世 篠原 沙世 • 更新: • 公開: • 読了約 14 分
目次

"Could you send me the CSV? Please enclose it in double quotes."

Have you ever been troubled by a request like this from a system administrator at a partner company?

Excel's "Save As → CSV" function does not add double quotes (hereinafter referred to as DQ). On the other hand, manually adding DQ to hundreds of lines of values is not realistic.

With VBA, you can output a CSV with all fields enclosed in DQ at the click of a button.

Moreover, it can correctly handle tricky cases such as "fields containing commas" or "fields containing DQ itself."

In this article, I will explain step-by-step, from the basics of DQ-enclosed CSV output to a complete version compliant with RFC 4180 (the international CSV specification).

What you will be able to create with this article

n9cc868887937

After reading this article, you will be able to do the following:

  • Output a CSV with all fields enclosed in DQ

  • Correctly output by escaping DQ within fields (" → "")

  • Output data containing commas within fields without breaking it

  • Choose a method to conditionally enclose only fields that require DQ

  • RFC 4180 (international CSV specification) fully compliant output

In the first half (free section), I will explain the basic mechanism and minimal code, and in the second half (paid section), I will explain the complete RFC 4180-compliant code, conditional DQ, five customization patterns, and how to deal with common errors.

Why are double quotes necessary?

First, let's organize the reasons why DQ-enclosed CSVs are required.

Problematic ordinary CSV
日付,取引先,商品名,金額
2025/01/15,株式会社ABC, 東京支店,えんぴつ,500

The second line, "ABC Co., Ltd., Tokyo Branch," contains a comma. Since the CSV delimiter is also a comma, the importing system will mistakenly recognize "ABC Co., Ltd." and " Tokyo Branch" as separate fields. As a result, the columns will shift and break.

CSV with DQ
"日付","取引先","商品名","金額"
"2025/01/15","株式会社ABC, 東京支店","えんぴつ","500"

If you enclose all fields in DQ, commas within fields will not be treated as delimiters. The importing side can correctly recognize the data.

RFC 4180 Rules

RFC 4180, the international specification for CSV, defines the following rules.

Since many systems and applications follow this specification, you will rarely encounter issues if you can output CSV that complies with RFC 4180.

Basic Code: Start with this to get it working

This is the minimal code to output CSV with all fields enclosed in double quotes (DQ).

Public Sub ExportCSVWithDQ_Basic()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim lastCol As Long
    Dim varData As Variant
    Dim rowIdx As Long
    Dim colIdx As Long
    Dim lineData As String
    Dim filePath As String

    Set ws = ThisWorkbook.Sheets("データ")

    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    ' データを配列に一括読み込み
    varData = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol)).Value

    filePath = "C:\Data\output_dq.csv"

    Open filePath For Output As #1

    For rowIdx = 1 To lastRow
        lineData = ""
        For colIdx = 1 To lastCol
            If colIdx > 1 Then lineData = lineData & ","
            lineData = lineData & """" & varData(rowIdx, colIdx) & """"
        Next colIdx
        Print #1, lineData
    Next rowIdx

    Close #1

    MsgBox "完了。" & lastRow & " 行を出力しました。"
End Sub
Key points of the code

"""" & varData(rowIdx, colIdx) & """"
In VBA code, """" represents a single DQ character. This is a bit confusing, but here is how it works.

"     → 文字列の開始
""    → DQ1文字を表すエスケープ
"     → 文字列の終了

つまり """" = DQ1文字

"""" & "Tanaka" & """" becomes the string "Tanaka".

Bulk reading into an array
We use varData = ws.Range(...).Value to retrieve sheet data into an array all at once. This is significantly faster than accessing ws.Cells() every time inside a loop.

The "three weaknesses" of this code

Weakness 1: DQs within fields are not escaped

If the data contains a DQ itself, such as Nickname"Tanaka", the output will look like this.

"ニックネーム"タナカ""

The DQ pairing breaks, and the importing system cannot correctly determine the field boundaries. According to RFC 4180, DQs within fields must be converted (escaped) to "".

Weakness 2: The output path is hardcoded

This is the same problem as the P4 article. You have to rewrite the code every time, making it unusable for those who cannot touch VBA.

Weakness 3: Dates become numbers (serial values)

Dates retrieved from an array using .Value are output as serial values (e.g., 45672). To output them as "2025/01/15", separate formatting conversion is required.

From this point on, I will release the "complete RFC 4180-compliant version of the code" that solves all three of these weaknesses.

In addition, I will explain all of the following content as well.

  • Implementing DQ escape processing

  • Implementing a file save dialog

  • Maintaining date and numeric formatting

  • How to conditionally enclose only fields that require DQs

  • 5 customization patterns useful for practical work

  • FAQ on common errors and solutions

Paid area starts here (500 yen)

同じカテゴリの記事

篠原 沙世

アニメとゲームの新作情報を担当。制作会社・配信元の公式告知と登壇情報を照合して記事化します。

おすすめの関連記事