どうも、あおです。
VB.NETでExcel操作する際、指定列の最終行を取得する方法。
以下サンプルソース。
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Excelオブジェクトを生成
Dim xlApp As New Excel.Application()
'指定したExcelファイルを開く
Dim xlBk As Excel.Workbook = xlApp.Workbooks.Open("C:\Users\user\Desktop\test.xls")
'シートの宣言と対象シートのセット(今回の場合のシート名「def」)
Dim xlTestSh As Excel.Worksheet = xlBk.Worksheets("def")
'最終行取得用宣言
Dim xlEndRg As Excel.Range = Nothing
'範囲選択用宣言
Dim xlSelRg As Excel.Range = Nothing
Try
'Excelを表示する
xlApp.Visible = True
'対象シートをアクティブにする
xlTestSh.Activate()
'最終行取得(今回の場合はB列の最終行を取得)
xlEndRg = xlTestSh.Range("B" & xlTestSh.Rows.Count).End(Excel.XlDirection.xlUp)
'範囲選択(A2セルからB列の最終行まで)
xlSelRg = DirectCast(xlTestSh.Range(xlTestSh.Cells(2, 1),
xlTestSh.Cells(CType(xlEndRg.Row, Integer), 2)), Excel.Range)
'セットした範囲を選択状態にする
xlSelRg.Select()
'処理終了のメッセージダイアログ表示
MessageBox.Show("処理終了しました",
"確認",
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly)
Catch ex As Exception
MsgBox(ex.Message)
Finally
'Excelの各プロセス解放
If Not xlEndRg Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlEndRg)
xlEndRg = Nothing
End If
If Not xlSelRg Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSelRg)
xlSelRg = Nothing
End If
If Not xlTestSh Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlTestSh)
xlTestSh = Nothing
End If
If Not xlBk Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBk)
xlBk = Nothing
End If
If Not xlApp Is Nothing Then
xlApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End If
GC.Collect()
End Try
End Sub
End Class
簡単に説明すると、
先にForm1というフォームをつくって、
ボタンを配置します。(今回の名前は「Button1」)
そして以下の流れ。
1)対象のExcelファイルの場所+ファイル名をセット
2)対象のシート名セット
3)対象のExcelを表示して、対象シートをアクティブにする
4)最終行取得(今回の場合はB列の最終行を取得)
5)一応、範囲選択(A2セルからB列の最終行まで)を実施
ちなみにセルの引数に指定するのは、
左がRow(行)で右がColumn(列)
xlTestSh.Cells(RowIndex, ColumnIndex)
A2セルの場合は、xlTestSh.Cells(2, 1)
どっちにどれを指定するか迷うよね~。
6)選択した範囲を選択状態にする
7)処理が終わった合図として、メッセージダイアログを表示
8)Excelの各プロセス解放
結果をExcelで確認したい場合、Excelを選択して、
ヘッダーのExcelファイル名をクリックすると、選択状態が表示されます。
以上、簡単にできそうでできなかった最終行取得。

