2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EXCELファイルのすべてのシートをCSVファイルで出力するマクロを作成してみた

Last updated at Posted at 2019-12-14

EXCELファイルの全シートをシート名のCSVファイル名で出力するVBAのサンプルを作成しました
また使いそうなので、忘れないうちにメモを残しておきます。

Sub outputCSV()

     '出力末尾列
     END_COL = 100

     '出力開始行
     START_ROW = 1

     '出力最大行
     MAX_ROW = 10000
         
     Dim sh As Worksheet
     
     '基底ファイルパス取得
     thisPath = ThisWorkbook.Path
      
     'シート毎のループ
     For sheetIndex = 1 To Worksheets.Count
     
        'シートオブジェクト取得
        Set sh = Worksheets(sheetIndex)
     
        'シート名取得
        sheetName = sh.Name
        
        '出力CSVファイル名生成
        Filepath = thisPath & "\" & sheetName & ".csv"

        '該当シート情報出力
        sh.Activate
        
        '出力CSV作成
        Open Filepath For Output As #1
        
        '1行ごとに行情報を出力
        For tgtRow = START_ROW To MAX_ROW
        
            '1行ごと取得、CSV文字列を生成
            Dim arr: arr = Range(Cells(tgtRow, 1), Cells(tgtRow, END_COL))
            Dim arrRowLine: arrRowLine = WorksheetFunction.Transpose(arr)
            Dim arrColLine: arrColLine = WorksheetFunction.Transpose(arrRowLine)
            '配列を区切り文字カンマ「,」で連結
            lineCsvStr = Join(arrColLine, ",")

            'CSV文字列出力
            Print #1, CStr(lineCsvStr)

        Next tgtRow
        
        'ファイルをClose
        Close #1
     
     Next sheetIndex
     
     MsgBox "CSV出力が完了しました"
   
End Sub

EXCELから1行ごとの行情報をまとめて取得する方法は以下を参考にさせていただきました。
https://thom.hateblo.jp/entry/2018/08/02/073503

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?