访问2010获得excel 2010中的最大行

时间:2013-06-21 10:35:21

标签: excel vba access-vba

我在通过MS Access 2010访问excel 2010时遇到问题。 从访问2010,我想从我的Excel数据获得最大行。 这是我的代码:

Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
Dim lastRow As Long, i As Integer
MySheetPath = "C:\Users\myaccount\Desktop\LRLV\mydata.xlsx"
Set Xl = CreateObject("Excel.Application")
Set XlBook = GetObject(MySheetPath)
Xl.Visible = True
XlBook.Windows(1).Visible = True
Set XlSheet = XlBook.Worksheets(1)
With XlSheet
lastRow = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End With

当我没有打开excel时,一切都还好。但是当我有一个或多个已打开的excel时,变量“lastRow”总是给我“类型不匹配”错误。现在我需要知道如何解决它。非常感谢你。

2 个答案:

答案 0 :(得分:0)

.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious)在此实例中未返回有效范围。这种测量结果不成功。这就是你得到类型不匹配的原因。

要解决,请执行以下操作:

Dim rng As Excel.Range

Set rng = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious)

If Not rng Is Nothing Then
    lastRow = rng.Row
Else
    'ToDo - handle the error here
EndIf

答案 1 :(得分:0)

您的问题是对A1的无限制引用。我也不确定为什么在已有应用程序引用时使用GetObject

Dim Xl As Excel.Application

Dim XlBook As Excel.Workbook

Dim XlSheet As Excel.Worksheet

Dim lastRow As Long, i As Integer

MySheetPath = "C:\Users\myaccount\Desktop\LRLV\mydata.xlsx"

Set Xl = CreateObject("Excel.Application")
Xl.Visible = True
Set XlBook = XL.Workbooks.Open(MySheetPath)

XlBook.Windows(1).Visible = True

Set XlSheet = XlBook.Worksheets(1)

With XlSheet

    lastRow = .Cells.Find(What:="*", After:=.Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

End With