VBA全局变量和Access数据库

时间:2015-07-12 05:12:48

标签: excel vba ms-access

我试图使用像这样的全局变量从数据库中获取数据......

ThisWorkBook

Private Sub Workbook_BeforeClose(Cancel As Boolean)
DB.Close
End Sub

Private Sub Workbook_Open()
DBfile = Application.ThisWorkbook.Path & "\mydatabase.accdb"
Set DB = DBEngine.OpenDatabase(DBfile)
End Sub

IN MODULE1

Option Explicit
Global DB As DAO.Database
Global RS As DAO.Recordset
Global DBfile As Variant

Public Function GetDataFromDB(TBL As String, COLMN As String, DTCLN As String, DT As String) As Variant

Set RS = DB.OpenRecordset("SELECT " & COLMN & " FROM " & TBL & " WHERE " & DTCLN & " = #" & Format(DT, "m\/d\/yyyy") & "#", dbOpenDynaset)

If RS.RecordCount > 0 Then
    RS.MoveFirst
    GetDataFromDB = RS(COLMN)
End If

End Function

Set RS = DB.OpenRecordset上我收到错误' 91'。

当我在函数中打开数据库时,一切正常,但我有很多这样的函数,所以如果我用每个函数打开数据库,Excel将会运行得更慢

请有人帮忙。

1 个答案:

答案 0 :(得分:1)

DBEngine是一种Access VBA方法。它在Excel VBA中不存在。

因此,您无法在Workbook_Open()中使用它。

您收到错误91,因为未设置DB对象变量。