事務屋さんの備忘録

主にプログラミングのことを書いていきます。メモというか備忘録的な感じで。プログラミングといっても、私はプロのエンジニアでも本職のプログラマーでもありません。単なる事務職をやってるサラリーマンで、空いた時間にちょこちょこっとプログラミングしてる程度です。よってこのブログに記載したことが誤っていたり、もっとよい方法がある場合もあると思います。その場合には、ご指摘いただけると嬉しいです。また、このブログを読んで役に立った、なんて方がいらっしゃったら幸いですね。

VB.NETでExcelを操作する

メモ。

Imports Microsoft.Office.Interop
Public Class Form1

    Dim strPath As String    'プログラムのパス(ファイル名を除く)

    Dim xlApp As Excel.Application = Nothing

    Dim xlBook As Excel.Workbook = Nothing
    Dim xlSheet As Excel.Worksheet = Nothing

    Dim xlBookWrite As Excel.Workbook = Nothing
    Dim xlSheetWrite As Excel.Worksheet = Nothing

    Dim myHash As Hashtable = New Hashtable()

    Dim intY As Integer

    Private Sub Form1_Load(ByVal sender As Object,
                           ByVal e As System.EventArgs) Handles Me.Load

        strPath = My.Application.Info.DirectoryPath '絶対パスの取得

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Excel が既に起動されているかどうかを調べます-------
        Try

            '第1引数を指定せずに GetObject 関数を呼び出すと、
            'アプリケーションのインスタンスへの参照が返されます
            'Excel が起動されていないと、エラーが発生
            '起動していればそのExcelを使用します
            xlApp = GetObject(, "Excel.Application")

        Catch ex As Exception

            'Excel が起動していないなら新規にインスタンスを生成します
            xlApp = CreateObject("Excel.Application")

        End Try
        '---------------------------------------------------


        xlApp.Visible = True 'エクセルを表示(表示しなくてもOK)


        Try

            '同一フォルダ内のエクセルファイルを掴む処理
            For Each strFName As String In System.IO.Directory.GetFiles(strPath, "*.*")

                Dim strExtension As String = System.IO.Path.GetExtension(strFName) '拡張子を取得

                Select Case LCase(strExtension)

                    'Excelファイルのみ取得
                    Case ".xls", ".xlsm", ".xlsb", ".xlsx", ".csv"  'GetExtensionは .も含む

                        xlBook = xlApp.Workbooks.Open(strFName) 'ファイルを開く

                        Check_Files()

                End Select

            Next


            Write_No() '書き込み処理


        Catch ex As Exception

            MessageBox.Show("予期せぬエラーが発生しました・・・", "Error!",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Exclamation)

        Finally

            '▼解放処理
            ' 既存ファイル
            MRComObject(xlSheet)
            MRComObject(xlBook)

            xlApp.Quit()
            MRComObject(xlApp)

            xlSheet = Nothing
            xlBook = Nothing

            xlApp = Nothing

        End Try

        MessageBox.Show("プログラムを終了します。", "Excel操作",
                        MessageBoxButtons.OK, MessageBoxIcon.Information)

        Application.Exit()

    End Sub

    Private Sub Check_Files()

        '1シート目をアクティブにします
        xlSheet = xlBook.Worksheets(1)
        xlSheet.Activate()

        If xlSheet.AutoFilterMode Then      'オートフィルタモードなら
            xlSheet.AutoFilterMode = False  '解除します
        End If

        If xlSheet.Cells(1, 1).Value = "Read_APP_Name" Then

            Dim intLastRow As Integer = xlSheet.Cells(xlSheet.Cells.Rows.Count, 1).End(Excel.XlDirection.xlUp).Row

            intY = 2
            Do Until intY > intLastRow

                'myHashにキーとアイテムを格納します
                myHash.Add(xlSheet.Cells(intY, 1).Value, xlSheet.Cells(intY, 2).Value)

                intY += 1
            Loop

            xlBook.Close(False)

        ElseIf xlSheet.Cells(1, 1).Value = "Write_APP_Name" Then

            '書き込み用変数にセットします
            xlBookWrite = xlBook
            xlSheetWrite = xlSheet

        Else

            xlBook.Close(False)

        End If

    End Sub

    Private Sub Write_No()

        xlSheetWrite.Activate()

        Dim intLastRow As Integer =
            xlSheetWrite.Cells(xlSheetWrite.Cells.Rows.Count, 1).End(Excel.XlDirection.xlUp).Row

        intY = 2
        Do Until intY > intLastRow

            'キーがHash内に存在するなら
            If myHash.ContainsKey(xlSheetWrite.Cells(intY, 1).Value) Then

                '値を書き込みします
                xlSheetWrite.Cells(intY, 2).Value = myHash(xlSheetWrite.Cells(intY, 1).Value)

            End If

            intY += 1
        Loop

        xlBookWrite.Save()
        xlBookWrite.Close(False)

        MRComObject(xlBookWrite)

    End Sub

    Private Sub MRComObject(ByVal objCom As Object) '■Comの解放処理

        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(objCom)
        Catch ex As Exception
            objCom = Nothing
        Finally
            objCom = Nothing
        End Try

    End Sub

End Class