0

我在通过 MS access 2010 访问 excel 2010 时遇到问题。从 access 2010 开始,我想从我的 excel 数据中获取最大行数。这是我的代码:

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

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

4

2 回答 2

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
于 2013-06-21T10:41:52.307 回答
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
于 2013-06-21T11:08:41.547 回答