connecting to a read-only Access db from Excel VBA - excel

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.
:-(

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

Excel VBA procedure crashes when opening a Access database connection/using Access Runtime

When executing a VBA procedure from Excel to connect to an Access database using Microsoft Access Runtime 2016 on my second laptop, the VBA procedure seems to freeze processing for a few seconds, crashes and closes the Excel application without triggering the error handler in my code so there is no error message for me to decipher. What can be the issue or how can I trap the error?
This VBA application works fine on my first laptop which has the full version of Access with no issues. The second laptop was working before I loaded Microsoft Access Runtime 2016. I was using a database application called "MDB Plus" which reads Access database files but now that doesn't work anymore.
I'm using the following:
OS: Windows 10,
MS Office: 2007,
MS Access Runtime 2007-2016,
Excel VBA 2007
To try to resolve this I: 1.) Uninstalled MS Access Runtime 2016 and the Excel application still crashed, 2.) Install MS Access Runtime 2007 and the Excel application still crashes.
Here is my code:
Sub TestGetTblPrimKey()
Dim oDBConn As ADODB.Connection
Dim sDBConnString As String
Dim moDBTblRecordSet As ADODB.Recordset
Const sDBTableLocPath As String _
= "C:\Users\kmass\AppData\Roaming\InvestManager\"
'
On Error GoTo ERROR_HANDLER
'
'Create Database connection
Set oDBConn = New ADODB.Connection
'Create Table Record-Set
Set moDBTblRecordSet = New ADODB.Recordset
'Build DB connection string
sDBConnString = _
"Provider=" & "Microsoft.ACE.OLEDB.12.0" & ";" _
& "Data Source='" _
& sDBTableLocPath _
& "tMeta_Table_Master.accdb" & "'"
'Open Database Table and Record-Set
oDBConn.Open sDBConnString '* <--CRASHES HERE
'
' Call ... the rest of the code to get record key
'
TestGetTblPrimKeyExit:
oDBConn.Close
'Release Table Objects
Set moDBTblRecordSet = Nothing
Set oDBConn = Nothing
Exit Sub
'
ERROR_HANDLER:
Debug.Print Err.Number & vbCrLf & Err.Description
Resume TestGetTblPrimKeyExit
'
End Sub
I expected the code to connect to the Access Database.
You can easily control Access from Excel, and do all kinds of things within the Access object, from Excel. Here are three simple demos of what you can do.
1)
'Open MS Access Form, from Excel
Global oApp As Object
Sub OpenAccess()
Dim LPath As String
Dim LCategoryID As Long
'Path to Access database
LPath = "C:\your_path_here\Northwind.mdb"
'Open Access and make visible
Set oApp = CreateObject("Access.Application")
oApp.Visible = True
'Open Access database as defined by LPath variable
oApp.OpenCurrentDatabase LPath
'Open form of interest
oApp.DoCmd.OpenForm "Form1"
End Sub
2)
'RUN MS ACCESS MACRO FROM EXCEL:
Sub AccessTest1()
Dim A As Object
Set A = CreateObject("Access.Application")
A.Visible = False
A.OpenCurrentDatabase ("C:\your_path_here\Northwind.mdb")
A.Application.Run "ExportToExcelTest"
End Sub
3)
' Run a delete query in MS Access, from Excel
Sub OpDaHus01()
Dim strDatabasePath As String
Dim appAccess As Access.Application
Dim strSQL As String
strDatabasePath = "C:\your_path_here\Northwind_2012.mdb"
strSQL = "DELETE tblTest.* FROM tblTest;"
Set appAccess = New Access.Application
With appAccess
.OpenCurrentDatabase strDatabasePath
.DoCmd.RunSQL strSQL
.Quit
End With
Set appAccess = Nothing
End Sub
If you need to run the code from a Macro, it needs to be a Public Function (rather than Sub), and it needs to be in a standard module (not a Form, Report or Class module).

VBA runtime error: could not find file

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.

ADODB connection to .mdb file from excel 2013

I hope someone can help.
I've developed an excel package that updates a .mdb access database through the connection string "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"
The database is shared.
I have a Mitel telephony system that checks the database every 10 seconds or so to check for a new entry.
The database is updated with
Dim q As New ADODB.Command
Dim cn As New ADODB.Connection
Dim SQL As String
SQL = "INSERT INTO tbl1LinkAuths (DateTimeAdded, DateEntered, AddedBy, REG, OrderNo,AccountNumber, CentreNumber, EmailAddress, Callback, "
SQL = SQL & "MakeText, "...............
cn.Open cnDB
q.ActiveConnection = cn
q.CommandText = SQL
'Excecute the above SQL to insert the new job record
q.Execute
Set rs = Nothing
Set cn = Nothing
Dim db As Access.Application
Set db = New Access.Application
db.Application.Visible = False
db.OpenCurrentDatabase "\\kffcis02\VWM Share\TelephonyDB.mdb", False
db.CloseCurrentDatabase
The INSERT statement updates the database fine, but I find I have to open and close the database to get it to update in time.
This package is used heavily by around 5 people at a time, making about 2 entries per minute.
It comes up with the error "file already in use", especially when using excel 2013, a lot of the time. I think this is because I have to open/close the database every time I update.
Does anybody know of a different way I can get the database to update quicker?
I've got the actual database setting to update ADODB every second and the database is shared.
I'm now desperate, as this package has went live. I didn't have any problems during testing because there wasn't as many people using it and none of them were on office 2013.
Wrong driver: Assuming a reference to activex data objects...
dim conn as adodb.connection 'module level variable
const DBNAME = "your name here"
const DBLOC = "Your dir here"
Sub UpdateDb()
dim sql as string
openconnectionroutine
sql = "INSERT INTO tbl1LinkAuths (DateTimeAdded, DateEntered, AddedBy, "
'etc
'if you want to check it worked : otherwise ditch numrecs
dim numrecs as long
conn.execute sql, numrecs
msgbox "You added " & numrecs & " records",vbokonly,"Done"
end sub
sub Openconnectionroutine()
if conn is nothing then set conn = new adodb.connection
if conn.connectionstring = "" then
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=" & DBNAME & ";" & _
"DefaultDir=" & DBLOC & ";" & _
"Uid=Admin;Pwd=;"
end if
if conn.state = adstateopen then
else
conn.Open
end if
End sub

Problem updating record in Access 2007 database from Excel Worksheet

I have a macro in my excel workbook that updates a specific record in the access database related to the spreadsheet.
All works fine if the access database is closed. Problems arise if the database is open and a user is editing the specific record that the excel spreadsheet relates to.`
I get the following Error Message:
Error Number 2147467259:
The database has been paced in a state by user 'ADMIN' on
'LAPTOP' that prevents it from being opened or locked.
I have set the database form's Record Locks to 'No Record Locks' but this hasn't helped.
Any advice or help is greatly appreciated.
Cheers
Noel
Public Sub updateAccessRecord()
On Error GoTo ProcError
Dim subFuncName As String
subFuncName = "updateAccessRecord"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset
Dim dbName As String
Dim dbPath As String
Dim strCon As String
Dim recID As Long
Dim fieldVal As Double
Dim strSQL As String
fieldVal = Worksheets("House Claim").Cells(593, 10).Value
dbName = "claim-db.mdb"
dbPath = ThisWorkbook.Path & "\..\..\..\..\"
dbPath = dbPath & "\" & dbName
strSQL = "UPDATE tblInsClaimDet SET propSet=" & fieldVal & " WHERE ID=" & recID & ""
Set conn = New ADODB.Connection
With conn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath
.Open
End With
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = strSQL
End With
Set rst = cmd.Execute
Set rst = Nothing
conn.Close
Set conn = Nothing
ExitProc:
Exit Sub
ProcError:
MsgBox "Error " & Err.Number & ": " & Err.Description, _
vbCritical, "Error in procedure in " & subFuncName
Resume ExitProc
End Sub
It seems that you have not split the database into a front-end and a back-end. The problem goes away if you do. Ctrl+S is not for saving a record, that is Shift+Enter, it is for saving a database object, and so it seems it has the effect of throwing the database into design or development state.
On the macro side; have you tried opening your connection as read-only? Even though your Access user is not locking the record, he has a "read lock" on the record, thereby preventing an exclusive lock by excel. I'm thinking that if both users are only attempting only read access, you should be Ok; but if either one is doing read/write, then it will fail.
On your access form, you should also have:
Me.AllowAdditions = True
Me.AllowDeletions = False
Me.AllowEdits = False
The problem is probably not in your code. The error:
The database has been paced in a state by
Indicates that the database has been opened in an exclusive mode. You should check how you are opening the database.

Resources