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
Related
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).
I have a problem whereby I have an excel vba macro which works perfectly on my local machine however when stored on a server crashes.
I have identified the point at which the macro crashes, and this is when the excel macro attempts to open the ADODB Recordset (Db is MS Access).
The folder structure in the code is identical to my desktop setup so I don't think this is the issue. Just seems to be when the excel file attempts to query the database when opening the ADODB recordset.
Any help much appreciated! If you need further info please let me know.
Thanks in advance!
EDIT:
Upon further investigation, I have verified opening and closing both the connection and recordset as working fine.
Its when I pass this query through as the source which causes excel to crash. Here is my code:
Dim DirectoryLocation As String
DirectoryLocation = Application.ActiveWorkbook.Path
Dim ConnString As String
ConnString = _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DirectoryLocation & "\Data\UK Sales.accdb;Persist Security Info=False;"
'Declare new database connection object
Dim DBConn As ADODB.Connection
'Set new database connection object
Set DBConn = New ADODB.Connection
'Declare new recordset object
Dim SalesData As ADODB.Recordset
'Set new recordset object
Set SalesData = New ADODB.Recordset
'Define connection string property of database connection object
DBConn.ConnectionString = ConnString
'Open database connection
DBConn.Open
'On Error GoTo CloseConnection
'Set parameter values for reporting
Dim Rep_Param As String
Rep_Param = Application.WorksheetFunction.VLookup(Worksheets("Dashboard").Range("C5"), Worksheets("Lookups").Range("H:I"), 2, 0)
Dim Rep_Option As String
Rep_Option = Worksheets("Dashboard").Range("C6").Value
'Get customer names for report and populate report
'------------------------Query---------------------'
Dim Cust_Billing_Qry As String
Cust_Billing_Qry = "SELECT DISTINCT Customer_Billing FROM Sales WHERE " & Rep_Param & "='" & Rep_Option & "'"
SalesData.Open Cust_Billing_Qry, DBConn
'On Error GoTo CloseRecordSet
Sheets("Revenue Analysis (Detail)").Range("C:C").ClearContents
Sheets("Revenue Analysis (Detail)").Range("C6").CopyFromRecordset SalesData
SalesData.Close
Any help much appreciated!
I have to create over 170 named ranges in Excel which I am trying to load into an Access table. Below is my code.
Sub Load_To_ALLL_TSD()
Dim strDatabasePath As String
Dim oApp As Access.Application
Dim PathOfworkbook As String
PathToDB = ThisWorkbook.Path
strDatabasePath = PathToDB & "\RAROC.accdb"
Set oApp = CreateObject("Access.Application")
'Set db = Application.CurrentProject
oApp.Visible = True
oApp.OpenCurrentDatabase strDatabasePath
Set db = CurrentDb()
Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)
With oApp
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
.Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
.Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
.Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value
' etc, etc, lot more fields and named ranges here
' add more fields if necessary...
.Update ' stores the new record
End With
End With
Set oApp = Nothing
MsgBox ("Done! All Data saved to RAROC database!!")
End Sub
I'm getting some weird errors! If I run the code using F8, it works fine. If I click a button to fire the code, sometimes it works and sometimes it doesn't work. I has errored out on several different lines.
Once it threw an error here:
Set rs = db.OpenRecordset("ALLL_TSD", dbOpenTable)
Error reads 'object variable or with block not set'
Once it said 'Microsoft Access has stopped working' and it threw an error on this line.
.Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
I've seen some other weird things too.
I have a reference set to both:
Microsoft DAO 3.6 Object Library
Microsoft Access 14.0 Object Library
It almost seems like I'm establishing a connection to Access and then almost immediately I lost the connection, somehow.
Finally, I have no Forms or Reports, and the DB is not split. I have just one single table in there now, which I am trying to write to. What can I try to resolve this?
Here's a basic example without using Access.
Needs a reference to Microsoft ActiveX Data Objects 2.x Library
Sub Tester()
Dim con As New ADODB.Connection, rs As New ADODB.Recordset
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source = " & ThisWorkbook.Path & "\RAROC.accdb"
'get an empty recordset to add new records to
rs.Open "select * from [ALLL_TSD] where false", con, _
adOpenDynamic, adLockBatchOptimistic
With rs
.AddNew
.Fields("TSD_Base_Rate_Received") = Range("TSD_Base_Rate_Received").Value
.Fields("TSD_Base_Rate_Received_Input") = Range("TSD_Base_Rate_Received_Input").Value
.Fields("TSD_Calculated_RAROC") = Range("TSD_Calculated_RAROC").Value
.Fields("TSD_Capital_Factor") = Range("TSD_Capital_Factor").Value
'etc...
.UpdateBatch '<< EDIT
.Close
End With
con.Close
End Sub
I'm following the instructions here http://software-solutions-online.com/excel-vba-export-worksheet-to-existing-access-table/ to transfer data from an Excel spreadsheet to an Access database. The script I have adapted is:
Sub MailMerge2()
Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
strPath = "C:...Documents\MailMerge2"
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath)
objAccess.Visible = True
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MyTable1", strExcelPath, _
True, "A1:D11")
End Sub
However, running this gives me an error saying:
Run-time error: 7866, Microsoft Access can't open the database
because it is missing, or opened exclusively by another user, or it is
not an ADP file.
Any suggestions on which of these the problem is? I'm fairly new to Access, and haven't quite got the hang of the terminology yet.
Found the problem. I left out .accdb in my Access db file names.
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.