配列を使用して、Visual Basic .NET から Excel を自動化して範囲内のデータを入力または取得する方法
概要
この記事では、Microsoft Excel を自動化する方法と、複数セル範囲に値の配列を入力する方法について説明します。 この記事では、Automation を使用して複数セル範囲を配列として取得する方法についても説明します。
詳細情報
セルを 1 つずつ入力せずに複数セル範囲を塗りつぶすには、Range オブジェクトの Value プロパティを 2 次元配列に設定できます。 同様に、値の 2 次元配列は、Value プロパティを使用して複数のセルに対して一度に取得できます。 次の手順は、2 次元配列を使用したデータの設定と取得の両方に関するこのプロセスを示しています。
Microsoft Excel 用の Automation クライアントをビルドする
Microsoft Visual Studio .NET を起動します。
[ファイル] メニューの [新規] をクリックし、[プロジェクト] をクリックします。 Visual Basic プロジェクトの種類から Windows アプリケーションを選択します。 既定では、Form1 が作成されます。
Microsoft Excel オブジェクト ライブラリへの参照を追加します。 これを行うには、次の手順を実行します。
- [ プロジェクト] メニューの [ 参照の追加] をクリックします。
- [COM] タブで、Microsoft Excel オブジェクト ライブラリを探し、[選択] をクリックします。
メモ Microsoft Office 2007 および Microsoft Office 2003 には、プライマリ相互運用機能アセンブリ (PIA) が含まれています。 Microsoft Office XP には PIA は含まれていませんが、ダウンロードできます。
[参照の追加] ダイアログ ボックスで [OK] をクリックして、選択内容を受け入れます。 選択したライブラリのラッパーを生成するように求められた場合は、[はい] をクリックします。
[表示] メニューの [ツールボックス] を選択し、ツールボックスを表示します。 Form1 に 2 つのボタンとチェック ボックスを追加します。
チェック ボックスの Name プロパティを FillWithStrings に設定します。
Button1 をダブルクリックします。 フォームのコード ウィンドウが表示されます。
Form1.vb の先頭に次を追加します。
Imports Microsoft.Office.Interop
コード ウィンドウで、次のコードを置き換えます
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click End Sub
置換後:
'Keep the application object and the workbook object global, so you can 'retrieve the data in Button2_Click that was set in Button1_Click. Dim objApp As Excel.Application Dim objBook As Excel._Workbook Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim objBooks As Excel.Workbooks Dim objSheets As Excel.Sheets Dim objSheet As Excel._Worksheet Dim range As Excel.Range ' Create a new instance of Excel and start a new workbook. objApp = New Excel.Application() objBooks = objApp.Workbooks objBook = objBooks.Add objSheets = objBook.Worksheets objSheet = objSheets(1) 'Get the range where the starting cell has the address 'm_sStartingCell and its dimensions are m_iNumRows x m_iNumCols. range = objSheet.Range("A1", Reflection.Missing.Value) range = range.Resize(5, 5) If (Me.FillWithStrings.Checked = False) Then 'Create an array. Dim saRet(5, 5) As Double 'Fill the array. Dim iRow As Long Dim iCol As Long For iRow = 0 To 5 For iCol = 0 To 5 'Put a counter in the cell. saRet(iRow, iCol) = iRow * iCol Next iCol Next iRow 'Set the range value to the array. range.Value = saRet Else 'Create an array. Dim saRet(5, 5) As String 'Fill the array. Dim iRow As Long Dim iCol As Long For iRow = 0 To 5 For iCol = 0 To 5 'Put the row and column address in the cell. saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString() Next iCol Next iRow 'Set the range value to the array. range.Value = saRet End If 'Return control of Excel to the user. objApp.Visible = True objApp.UserControl = True 'Clean up a little. range = Nothing objSheet = Nothing objSheets = Nothing objBooks = Nothing End Sub
Form1 のデザイン ビューに戻り、Button2 をダブルクリックします。
コード ウィンドウで、次のコードを置き換えます
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click End Sub
置換後:
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim objSheets As Excel.Sheets Dim objSheet As Excel._Worksheet Dim range As Excel.Range 'Get a reference to the first sheet of the workbook. On Error Goto ExcelNotRunning objSheets = objBook.Worksheets objSheet = objSheets(1) ExcelNotRunning: If (Not (Err.Number = 0)) Then MessageBox.Show("Cannot find the Excel workbook. Try clicking Button1 to " + _ "create an Excel workbook with data before running Button2.", _ "Missing Workbook?") 'We cannot automate Excel if we cannot find the data we created, 'so leave the subroutine. Exit Sub End If 'Get a range of data. range = objSheet.Range("A1", "E5") 'Retrieve the data from the range. Dim saRet(,) As Object saRet = range.Value 'Determine the dimensions of the array. Dim iRows As Long Dim iCols As Long iRows = saRet.GetUpperBound(0) iCols = saRet.GetUpperBound(1) 'Build a string that contains the data of the array. Dim valueString As String valueString = "Array Data" + vbCrLf Dim rowCounter As Long Dim colCounter As Long For rowCounter = 1 To iRows For colCounter = 1 To iCols 'Write the next value into the string. valueString = String.Concat(valueString, _ saRet(rowCounter, colCounter).ToString() + ", ") Next colCounter 'Write in a new line. valueString = String.Concat(valueString, vbCrLf) Next rowCounter 'Report the value of the array. MessageBox.Show(valueString, "Array Values") 'Clean up a little. range = Nothing objSheet = Nothing objSheets = Nothing End Sub
Automation クライアントをテストする
- F5 キーを押してビルドし、サンプル プログラムを実行します。
- Button1 をクリックします。 Microsoft Excel は新しいブックで開始され、最初のワークシートのセル A1:E5 に配列の数値データが入力されます。
- Button2 をクリックします。 プログラムは、セル A1:E5 のデータを新しい配列に取得し、結果をメッセージ ボックスに表示します。
- FillWithStrings を選択し、Button1 をクリックしてセル A1:E5 に文字列データを入力します。
関連情報
配列を使用して以前のバージョンの Visual Studio で Excel データを設定および取得する方法の詳細については、以下の記事番号をクリックして、Microsoft サポート技術情報の記事を参照してください。
247412 INFO: Visual Basic から Excel にデータを転送するメソッド