I'm trying to get data from a database using global variables like this...
In 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
On Set RS = DB.OpenRecordset ~ I get an error '91'.
Everything works fine when I open the database within the function, but I have a lot of functions like this, so if I open the database with every function Excel will work slower
Can anyone help, please.
Sub Workbook_Openhasn't been started,. When I started it , everything worked. )))