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

概要

CSV情報をExcelに取り込んでなにかしたい場合の備忘録。

目的

CSVの情報を利用したいけどメモ帳のデータを一つずつ修正するのは骨が折れます。
そのような際に一旦Excelへ取り込み、修正を行うことで楽になります。
ここではCSVファイルを読み込みCollectionへ格納するところまでを記載します。

実装

取得処理を関数化し、作ってみます。

Public Function importCsv(path As String, headerSkip As Boolean) As Collection

    Dim data As Variant
    Dim result As New Collection
    Dim items As New Collection
    Dim header As Boolean: header = False
    
    Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' 以下UTF-8用、Unicodeを読み込む場合は第四引数に[-1]を設定する。
    Dim ts As Object: Set ts = fso.OpenTextFile(path, 1, False, 0)
    
    If headerSkip Then
        Call ts.ReadLine
    End If
    
    Do Until ts.AtEndOfStream
        Set items = New Collection
        data = Split(ts.ReadLine, ",")
        For Each Item In data
            items.Add Item
        Next
        result.Add items
    Loop

    ts.Close
    Set importCsv = result
End Function

引数で取得対象のファイルパスとヘッダの取得有無を指定し、Collectionで返却しています。

上記関数を使用する場合は以下のように記載します。

Public Sub main()
    Dim data As Collection
    Set data = importCsv("D:\local\desktop\test.csv", False)
    
    ' 行いたい処理を記載する
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?