0

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.

4
  • 1
    Try watch in debugger is there 'DB' empty or not. Cause after error vba reset all global variables. You might get some error before GetDataFromDB running so DB is not set Commented Jul 12, 2015 at 6:02
  • Thanks for your answer. The problem was that Sub Workbook_Open hasn't been started,. When I started it , everything worked. ))) Commented Jul 12, 2015 at 6:09
  • i'm not figure how you do that. Is workbook_open run automatic when excel open file? But if it's help - good one, but be careful with global vars Commented Jul 12, 2015 at 6:15
  • I think it has been turned off somehow (maybe after error), so it worked when I run it again. Commented Jul 12, 2015 at 6:28

1 Answer 1

1

DBEngine is an Access VBA method. It does not exist in Excel VBA.

You therefore cannot use it in Workbook_Open().

You get error 91 because the DB object variable is not set.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer . how to do that then ?
Use ADO from Excel VBA to connect to the database.
I think ADO is a bit slower than DAO. I have already managed the problem. But thanks again for your answer. )
From Excel you will not see a difference in speed between ADO and DAO, but ADO is significantly newer technology and offers an upgrade path, while DAO does not. At any rate, if my answer helped, please accept it.
OK. Which one will work on MAC OS ? I'm going to test my code on mac, so I just don't know if any of these will work on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.