访问VBA维度仅在第一次运行时存储期望值

时间:2013-04-11 01:59:26

标签: ms-access ms-access-2007 access-vba ms-access-2010

我已经从其他地方改编了这段代码。单击表单上的按钮,它意味着告诉我Excel电子表格中给定单元格范围内的非空行数(C1:C500)......

Sub ImportDataFromRange()

Dim excelapp As Excel.Application
Set excelapp = CreateObject("excel.application")
excelapp.Workbooks.Open (Application.CurrentProject.Path & "\MattExcelFile.xls")

Dim myrange As Range
Set myrange = excelapp.Sheets("Sheet1").Range("C1:C500")

Dim numberofrows As Integer
numberofrows = Excel.Application.WorksheetFunction.CountA(myrange)

MsgBox numberofrows
Debug.Print excelapp

excelapp.Quit
Set excelapp = Nothing

End Sub

Private Sub Command0_Click()

ImportDataFromRange

End Sub

在打开MS-Access并通过我创建的按钮运行此代码时,它第一次正常工作,但之后不再正常工作。关闭并重新打开MS-Access会重置该行为,以便在打开后第一次运行时再次正常工作,但永远不会再次运行。

首次运行时,这是存储在维度中的(正确)数据:

excelapp =“C:\ Users \ Matt \ Desktop \ MattExcelFile.xls” numberofrows = 4

在后续运行中,这是存储在维度中的(不正确的)数据:

excelapp =“Microsoft Excel” numberofrows = 500

有人可以帮我解决这里的代码,这样我就可以在同一个MS-Access会话中多次运行代码并每次都在维度中获取正确的数据吗?非常感谢。

2 个答案:

答案 0 :(得分:2)

刚刚对您的代码进行了一些更改 - 我为您注意到它们 - 对我有用。

至于excelapp维度,我认为它说'Microsoft Excel'是正确的,如果你要打印wb.Name维度,你将获得工作簿名称。不确定为什么它会在后续运行中为您提供不同的维度,可能是因为您没有明确关闭工作簿,但这是一个猜测。

Sub ImportDataFromRange()
Dim excelapp As Object
Set excelapp = CreateObject("excel.application")

' assign the workbook
Dim wb As Object
Set wb = excelapp.Workbooks.Open(Application.CurrentProject.Path & "\tbl_Order_Status.xls")


Dim numberofrows As Integer
' Call function slightly differently
numberofrows = excelapp.Application.counta(wb.worksheets("Sheet1").Range("C1:C500"))

' Close and release wb
wb.Close
Set wb = Nothing

MsgBox numberofrows
Debug.Print excelapp

excelapp.Quit
Set excelapp = Nothing

End Sub

答案 1 :(得分:1)

我认为您的问题源于您创建excelapp对象变量,但在获取{Excel.Application.WorksheetFunction上使用不同的引用(excelapp.WorksheetFunction而不是numberofrows)这一事实{1}}。

以下(更正的)代码适用于我:

Sub ImportDataFromRange()
Dim excelapp As Excel.Application
Set excelapp = New Excel.Application

excelapp.Workbooks.Open (Application.CurrentProject.Path & "\MattExcelFile.xls")

Dim myrange As Range
Set myrange = excelapp.Sheets("Sheet1").Range("C1:C500")

Dim numberofrows As Integer
numberofrows = excelapp.WorksheetFunction.CountA(myrange)

MsgBox numberofrows
Debug.Print excelapp

Set myrange = Nothing
excelapp.Quit
Set excelapp = Nothing

End Sub

Private Sub Command0_Click()

ImportDataFromRange

End Sub