わたろぐ

仕事、読書、ガジェット、グルメ、写真、旅行など雑多な備忘

【VB.net】 CSVファイルを取り込み、構造体の配列にセットする

FormLoad時にexeと同じディレクトリにあるinput.csvファイルを取り込む。 CSVは5列とし、1列目、2列目には数字のみ入るものとする。

Public Class Form1

    ' Form内で使用する共通の変数をセット
    Private sp() As Splr
    Private Max As Integer

    'FormLoad時にインプットとなるCSVファイルをグローバル変数の構造体の配列にセットする。
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim fileName As String = "Input.csv"    'ファイルのパス
        Dim fileNo As Integer = FreeFile()              'ファイル番号を取得
        Dim n As Integer = 0
        Dim seq As Integer = 0

        FileOpen(fileNo, fileName, OpenMode.Input)
        Do Until EOF(fileNo)        'ファイルの最後までループ
            ReDim Preserve sp(n)
            ' CSV各項目をセット
            Input(fileNo, sp(n).col1)
            Input(fileNo, sp(n).col2)
            Input(fileNo, sp(n).col3)
            Input(fileNo, sp(n).col4)
            Input(fileNo, sp(n).col5)
            'カウンタを進める
            n += 1
        Loop
        '結果行数をセット
        Max = n - 1
        FileClose(fileNo)

    End Sub

    Private Structure Splr
        '5列のCSVファイルを想定
        Dim col1 As Integer
        Dim col2 As Integer
        Dim col3 As String
        Dim col4 As String
        Dim col5 As String
    End Structure


End Class