VBA runtime error: could not find file - excel

Good day all. I have a problem that I simply cannot seem to solve. I am working on an excel program that retrieve data from and update an MS Access 2010 db. I am connecting with the db using ADODB.Connection and the file (access.accdb) resides in a file server. When the application first launches it uses form1 to get logon details from the user and checks if the user id exists within the db. This function resides within a module and works fine. When I attempt to open the same file from a sub within another user form (form2) I keep getting an error that the file could not be found. I am using the exact same path string as what is used within the module only that this time it is used from within a user form. Below is the code within Module2:
Dim con As Object
Dim rs As Object
Dim path As String
path = "path.accdb"
Set con = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
with con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source = " & path & "; Jet OLEDB:Database Password = pwd"
.Open
This works fine.
I use the same only from a user form and without the recordset object. I am not retrieving data from the form but rather updating the db. The form is used for data capturing only.
Any help will be appreciated. Thanks.
This is the code that I am using within form1:
Dim conn As Object
Dim strPath As String
strPath = "path.accdb" 'same as the path I used from within Module2
Set conn = CreateObject("ADODB.Connection")
with conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source = " & strPath & "; Jet OLEDB:Database Password = pwd"
.Open 'this is where I get the error.
'Rest of code
Error message:
Run-time-error '-2147467259 (80004005)':
Could not find file 'path.accdb'
I have checked the path and it is correct. I have checked for missing references. I must also mention that the database file is located on a folder on my company folder to which I do have access.

Simple syntax problem:
You declare strPath:
Dim strPath As String
strPath = "path.accdb" 'same as the path I used from within Module2
But then you call Path instead:
.ConnectionString = "Data Source = " & path & "; Jet OLEDB:Database Password = pwd"
It happens to all of us when we switch around the spelling of variables :)
** EDIT **
Ok... Let's try something different...
Why don't you open your database only once into a global variable?
Maybe opening it a second time in a subform is somehow clashing with your initial connection to the database.
Especially since you don't show us code where you close your connection.
A lot of clues are in your real code that you are not showing us. If making a global variable doesn't work, you may need to show us your real code with only sensitive info changed.

Related

Connect Excel to Access Form via VBA

I wanted to connect my Excel to my Access DB.
I want to extract Data from a Form into Excel.
Sub GetDataFromDB()
Dim conn As Object
Dim DBPATH, PRVD, connString, query As String
DBPATH = "...."
PRVD = "Microsoft.ace.OLEDB.12.0;"
connString = "Provider=" & PRVD & "Data Source=" & DBPATH
Set conn = CreateObject("ADODB.Connection")
conn.Open connString
DoCmd.OpenForm Forms![frm_name], acFormDS, "", "", , acNormal
(Do Something)
End Sub
Now I get an error 424 that an Object is needed but I don't know to to get access to that specific Form in my DB.
Can someone help me please?
Best regards
Normally you get your data form a table or a query. May be you should
explain better what you want to accomplish. Getting data directly from
a form doesn't sound logical. If you want to open an access form try;
Ps, Dim declarations are not correct, Dim x as string, y as string
otherwise they will be variant.
Public Sub Displayform(conPath As String)
Dim objAccess As Access.Application
'Check that this is the path on YOUR PC for
'Northwind.mdb, which ships with Access.
'Const conPATH = "C:\Users\Myname\documents\PrintMe.accdb"
'Create an instance of the Access application object.
Set objAccess = CreateObject("Access.Application")
'Access and display the application window.
objAccess.OpenCurrentDatabase conPath
objAccess.Visible = True
'Open the Employees form.
'objAccess.DoCmd.OpenForm "Cust List"
' Maximize other Access window and quit current application.
objAccess.DoCmd.RunCommand acCmdAppMaximize
Application.DoCmd.RunCommand acCmdAppMinimize
End Sub

Struggling to open access database from excel - error 91

I'm struggling opening a database from excel.
I'm want to retrieve some information and populate comboboxes.
I tried pasting the code in a standard module, and running it inside the userform module.
I run the code when the userform initializes.
First the code:
Dim dbe As DAO.DBEngine
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qry As String
On Error GoTo ERR_BBDD
'This is the line where the error is thrown.
Set db = dbe.OpenDatabase("E:\myDB.mdb")
I get error 91 "variable or with block not defined blah blah".
I checked if the .mdb file path is ok and it is.
The code is really simple but I must be missing something and can't find a reason for it to be failing, since as I read in all the docs and the internet, my code should work fine.
It looks like you're trying to open Access (for DAO) as you would from inside of an Access application instance, but you're in Excel. I don't think Excel has a DBEngine for you to call. You could open Access as a new Access.Application instance, then do your operations, but it will literally open an Access instance in the background which is not really efficient for a few lookups.
Instead I would suggest creating an ADODB connection, load your lookups, then close it.
Set objCnn = CreateObject("ADODB.Connection")
objCnn.Provider = "Microsoft.Jet.OLEDB.4.0"
objCnn.Open strDir & "\MyDatabase.mdb"
Set rst = CreateObject("ADODB.Recordset")
rst.Open strSQL, objCnn, adOpenStatic
Do Until rst.EOF
... do some lookup loading stuff here
rst.MoveNext
Loop
rst.Close
Hope that works!

connecting to a read-only Access db from Excel VBA

I have been a long-time visitor to stackoverflow, but this is my first question.
I'm trying to query an Access 2010 database in a folder to which the user has only read-only access.
strDBPath = <full path of accdb>
Set myConn = New ADODB.Connection
myConn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Mode=Read; Data Source=" & strDBPath
Set myRS = New ADODB.Recordset
myRS.ActiveConnection = myConn
The myConn.Open line gives a "file currently in use" error. If I move the accdb to a folder that the user can write, the code runs fine.
Thanks in advance for any advice!
Wie have also a connection with an Access DB but im quite sure we have also write permissions on the folder.
The Code we use is here.
Dim DB As DAO.Database
Dim QRY As DAO.QueryDef
Dim Rs As DAO.Recordset
Public Ersteller As String
'Prüft die Verbindung zur DB
Public Function OpenDB() As Integer
'Informationen über Database'
Dim Database As Variant
Database = Worksheets("Anträge").Range("B3").Value
'Check Datenbank Verbindung
On Error Resume Next
Set DB = CreateObject("DAO.DBEngine.120").OpenDatabase(Database)
If Err.Number <> 0 Then
MsgBox "Keine Verbindung zur Datenbank möglich!"
End If
OpenDB = Err.Number
End Function
Mayebe it helps. :)
Access to database in a read only folder is possible (of course Mode=Read) but only if this database is not used by any other user (it means there is no .ldb file). But then, there is only one user able to have an access. So anyone calling database (even if it is done by excel) locking it for any others.
:-(

Emulating a SHIFT key press when using VBA to open an ms-access database secured by an mdw file?

I want to run recursively through a directory of *.mdb files and search them to see which ones have a specific linked table.
These files are secured using several *.mdw files. I did not write any of them, but I am their maintainer.
I've found a way to do this, but it's too interactive; I need it to be non-interactive; since some of these *.mdbs I'm searching use an Autoexec macro.
From what I understand executing an Autoexec macro can be avoided if one holds the SHIFT key while opening them; however I use the command line in my macro to open these files, and there doesn't seem to be a way to hold the shift key.
I've found another example, which does allow you to hold down the shift key to avoid the Autoexec macro (see Bypassing Startup Settings When Opening a Database), but which does not allow you to unlock the database with an *.mdw file, because the OpenCurrentDatabase() method does not have a parameter for an *.mdw file
If your goal is simply to check whether a db file contains a specific linked table, you can use the ADO OpenSchema method. With that approach, you don't need to open the db file in an Access application session, so the AutoExec macro does not run.
Below is an example using late binding. I left comment notes in case you prefer early binding. Change the Provider if your Access version is older than 2007.
Since you're using Access user-level security, you will also have to adapt the connection string to include the path to your MDW and supply the Access security user name and password. Here is an example connection string (using the Jet 4 provider) from ConnectionStrings.com. I split the single-line string on the semicolons for readability:
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\mydatabase.mdb;
Jet OLEDB:System Database=system.mdw;
User ID=myUsername;
Password=myPassword;
Public Function HasLinkedTable(ByVal pDb As String, _
ByVal pTable As String) As Boolean
Const adSchemaTables = 20&
Dim cn As Object ' ADODB.Connection
Dim rs As Object ' ADODB.Recordset
Dim strConnect As String
Dim blnReturn As Boolean
strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & pDb & ";"
'Set cn = New ADODB.Connection
Set cn = CreateObject("ADODB.Connection")
cn.Open strConnect
Set rs = cn.OpenSchema(adSchemaTables)
With rs
Do While Not .EOF
If !TABLE_NAME = pTable And !TABLE_TYPE = "LINK" Then
'Debug.Print !TABLE_NAME, !TABLE_TYPE
blnReturn = True
Exit Do
End If
.MoveNext
Loop
.Close
End With
cn.Close
Set cn = Nothing
HasLinkedTable = blnReturn
End Function

Is it possible to embedded a Sqlite database into an excel 2007 file (zip archive)

I'm working on an excel application that requires a database back end. My preference is to use SQLite 3 and to make this as seamless and portable as possible for the end user.
Recently I have learned that an Excel 2007 file is simply a zip archive with a xlsm extension. My question is this, can I store my back-end SQLite 3 database in the Zip archive and use ODBC to interact with the database. If so, can anyone point me to some background information, articles, guidance on achieving this objective. Are there any downsides to this approach or a better alternative I should know about.
Thanks for your input.
Some notes. So far, no one has complained that the file does not open. Note that the Excel file is saved before the ADO code is run.
Very hidden:
ThisWorkbook.Worksheets("Courses").Visible = xlVeryHidden
ThisWorkbook.Worksheets("System").Visible = xlVeryHidden
A snippet of code:
Const gCN = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
<...>
Set rs = CreateObject("ADODB.Recordset")
Set cn = CreateObject("ADODB.Connection")
Set fs = CreateObject("Scripting.FileSystemObject")
scn = gCN & ThisWorkbook.FullName _
& ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
cn.Open scn
''If they do not have an ID, they do not exist.
sSQL = "SELECT ID,FirstName,LastName, " _
& "CourseName,AdditionalText,Format(ExpiryDate,'dd/mm/yyyy') As ExpiryDate " _
& "FROM [Applicants$] WHERE DateCancelled Is Null AND ID Is Not Null " _
& "AND (FirstName Is Null OR LastName Is Null Or CourseName Is Null " _
& "Or ExpiryDate Is Null) " & sWhere
rs.Open sSQL, cn
References:
Excel ADO
Connection strings
Most of the methods available to Jet can be used with Excel
Fundamental Microsoft Jet SQL for Access 2000
Intermediate Microsoft Jet SQL for Access 2000
Advanced Microsoft Jet SQL for Access 2000
Edit re Comments
I did not find the leak particularly bad, but I did not run many iterations, and this is quite a good machine.
The code below uses DAO, which does not cause a memory leak.
'Reference: Microsoft Office 12.0 Access Database Engine Object Library
Dim ws As DAO.Workspace
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sDb As String
Dim sSQL As String
sDb = ActiveWorkbook.FullName
Set ws = DBEngine.Workspaces(0)
Set db = ws.OpenDatabase(sDb, False, True, "Excel 8.0;HDR=Yes;")
sSQL = "SELECT * FROM [Sheet1$];"
Set rs = db.OpenRecordset(sSQL)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i)
Next
rs.MoveNext
Loop
rs.Close
db.Close
ws.Close
'Release objects from memory.
Set rs = Nothing
Set db = Nothing
Set ws = Nothing
Acknowledgement: http://www.ozgrid.com/forum/showthread.php?t=37398
Here is an alternative.
1) At Open (EVENTs in VBA) unzip from Excel .xlsm, sqlite and dbFile.
2) Process what you .....
3) At save (EVENTs in VBA) the book an then attach the Excel .xlsm ,sqlite , dbFile in Excel .xlsm.
Excel rewrites the file every time it is saved, so your own added file would be deleted.
Furthermore, there is no SQLite driver that can access database files inside of zip archives.
You would have either to ship the database file alongside with the Excel file, or to recreate the database with a list of SQL commands when your application detects that the DB file is missing.
This still requires that some SQLite (ODBC) driver is installed on the user's machine.
The most seamless and portable way to store data in an Excel file is to store it in an Excel sheet, as mentioned by Remou. However, it's possible that the ADO driver will refuse to open the file when it's already open in Excel, so that you have to use Excel functions to access the data.
Try using http://code.google.com/p/pyinex/
this embed the Python interpreter in Excel

Resources