ray88’s diary

お仕事で困ったとき用の自分用の覚書

AccessVBA Excelの最終行を取得する

■AccessVBAで参照設定をせずにExcelの最終行を取得する

Sub excelTest()
'------------------------------------
'Excelの最終行を取得する
'------------------------------------
    Dim xlApp As Object
    Dim wb As Object
    Dim i As Integer
    Dim strTargetpath As String
    Dim strPassword As String
    Dim intTargetRow As Integer
    '参照設定しない場合は「xlUp」の定数の値「-4162」で設定する
    Const xlUp As Integer = -4162    
    strTargetpath = "C:\デスクトップ\テスト.xlsx"    
     'ExcelApplicationインスタンス化
    Set xlApp = CreateObject("Excel.Application")
    Set wb = xlApp.Workbooks.Open(strTargetpath, Password:=strPassword)
     wb.sheets("Sheet1").Activate
    With wb.sheets("Sheet1")
        wb.ActiveSheet.Unprotect Password:=strSheetPW
        '-4162は定数「xlUP」の値/参照設定しない場合「Rows」も使えないのでExcelの最終セルアドレスを指定
        intTargetRow = .Range("A65536").end(xlUp).Row
        Debug.Print intTargetRow
    End With    
    wb.Close
    Set wb = Nothing
End Sub