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!
Related
I am using an Excel macro to define a data range in Excel and then call "objAccess.DoCmd.TransferSpreadsheet" to import the data from this range into an Access table. This import does not work all of the time.
I have come to the conclusion that the macro works fine when there is only one instance of Excel open. However, the data import fails when another instance is already open. In the latter case the Access database opens up and the Excel file from which I run the macro is being reopened (in read-only mode) in the other Excel instance. There is no actual error but the desired import is not being carried out. Why does this happen?
Sub Excel_2_Access()
Dim strPath As String
Dim strwbPath As String
Dim strRange As String
Dim objAccess As Access.Application
Dim wbActive As Workbook
'get database path
strPath = Worksheets("error").Range("Access_DB_Path").Value & "\" & Worksheets("error").Range("Access_DB").Value
'open database
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath)
objAccess.Visible = True
'access import
Worksheets("error").Columns("P:P").Calculate
Set wbActive = ActiveWorkbook
strwbPath = Application.ActiveWorkbook.FullName
strRange = "error!M2:M" & (Worksheets("error").Range("WKN_count").Value + 2)
Call objAccess.DoCmd.TransferSpreadsheet(acImport, 8, "WKN_Mapping", strwbPath, True, strRange)
objAccess.Forms("MX_Import").Refresh
End Sub
As the macro is fairly short I have included the entire code for your reference. However, I don't think the way the range is specified or names are provided is really relevant to the question.
The desired outcome would be to have an Excel macro in place that carries out the transfer from Excel to Access no matter if there are other instances of Excel open or not.
Is there such a thing as the primary instance of Excel (the first one that was opened) which has a special status? Is there a way to provide the specific Excel instance the workbook is in when calling the Access function from Excel? Or is there a more reliable way to transfer the data which generally avoids this problem with multiple instances?
I tested approach that opens Access db and runs TransferSreadsheet. Don't need to set a workbook object (your code sets but then doesn't even utilize). It ran without error every time. I tried setting the Access object Visible but the database appears and immediately closes anyway, although the data import does happen. Set reference libarary: Microsoft Access x.x Object Library.
Sub test()
Dim ac As Access.Application, strRange As String
Set ac = New Access.Application
strRange = "Sheet1!A1:E3"
ac.OpenCurrentDatabase "C:\Users\June\LL\Umpires.accdb"
ac.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Rates", ThisWorkbook.FullName, True, strRange
End Sub
Example Excel VBA code that exports all rows of worksheet to existing table in Access without opening Access file. Setting an ADODB connection makes the Execute method available. This approach runs faster. Set reference library: Microsoft ActiveX Data Objects x.x Library.
Sub test()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=Excel 8.0"
cn.Execute "INSERT INTO Rates(RateLevel, Rate, Pos, EffDate) IN 'C:\Users\June\LL\Umpires.accdb' " & _
"SELECT RateLevel,Rate,Pos,EffDate FROM [Sheet1$];"
cn.Close
Set cn = Nothing
End Sub
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.
I import data from an Access database just fine. However, I want to make the DB a runtime (.accdr instead of .accde). The Runtime works fine, too, on its own, but I cannot import data from a runtime application when in Excel (it does not permit it).
How can I contact my database and have a Runtime mode?
Nothing on the web I have found even mentions this problem. I have no problem with opening an ADODB connection with VBA if it is required.
Since ACCDR databases are not displayed among the choices offered by Excel's Data>From Access option, you can open a recordset to retrieve your Access data and then use Excel's CopyFromRecordset Method to save those data into a worksheet.
This code uses a DAO recordset loaded from an ACCDR database file and saves the data in the active worksheet ...
Const cstrDbPath As String = "C:\share\Access\Database2.accdr"
Const cstrDao = "DAO.DBEngine.120"
Dim dbe As Object ' DAO.DBEngine
Dim db As Object ' DAO.Database
Dim rs As Object ' DAO.Recordset
Dim strSql As String
strSql = "SELECT 'Hello World' AS greet_world;"
Set dbe = CreateObject(cstrDao)
Set db = dbe.OpenDatabase(cstrDbPath, True)
Set rs = db.OpenRecordset(strSql)
Range("A2").CopyFromRecordset rs
rs.Close
db.Close
That code uses DAO with late binding. If you prefer early binding, add "Microsoft Office <version> Access database engine Object Library" to your project's references.
Or if you prefer ADO, CopyFromRecordset will also work with an ADO recordset.
within my Excel sub I am calling an Access sub procedure that runs in the background (DB does not open) and updates a table in my DB. Everything works perfect, except that my Excel Sub will not proceed to the next line of code until Access is done running it's sub I called from Excel. So, my question is this...is there any way to call/run an Access Macro/Sub procedure from within an Excel Sub and have Excel proceed through the rest of the code and not have to wait for the Access Macro/sub to finish in order to proceed? Code: below:
Set acObj = CreateObject("Access.Application")
acObj.Application.Visible = False
acObj.OpenCurrentDatabase "C:\Intraday Data\Intraday.accdb"
acObj.Application.Run "RunData"
MsgBox "Done!"
So Basically I want to get the done prompt right away w/o having to wait 30 seconds for the access procedure to finish...anyone have any insight on this they can share w/ me please?
Thanks!
Here's some simple code to demonstrate an asynchronous call to an Access procedure:
Sub ExecuteAccessActionQuery()
' Sample demonstrating how to execute an action query in an Access accdb asynchronously
' Requires a reference to a Microsoft ActiveX Data Objects library
Dim cn As ADODB.Connection
Dim strQuery As String
Dim strPathToDB As String
Dim dTimer As Double
' Change path and query name as necessary
strPathToDB = "C:\some path\database name.accdb"
strQuery = "qmtTempTable"
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & strPathToDB & ";"
.Open
End With
dTimer = Timer
cn.Execute strQuery, , adCmdStoredProc + adAsyncExecute
MsgBox Timer - dTimer
Set cn = Nothing
End Sub
You can emulate an asynchronous call in VBA by creating a trigger in the client application which will then execute the required subroutine. This technique is described well here (note the 1 second time delay required a few posts down):
http://social.msdn.microsoft.com/Forums/en-US/0546f8eb-d786-4037-906e-1ee5d42e7484/asynchronous-applicationrun-call?forum=isvvba
Currently, you are manipulating data in the Access tables without initiating the application, so you can either use a new instance of Excel in which to create the trigger, or you can open the Access application and do it there (http://msdn.microsoft.com/en-us/library/office/aa213969%28v=office.11%29.aspx). Either way, you must have another independent application (process) within which to execute your 'asynchronous' routine.
Hey all, have been working on designing a new database for work. They have been using Excel for their daily reports and all the data is stored in there, so I decided to have the back-end of the database in Access and the front-end in Excel, so any analytical work can be easily performed once all the data has been imported into Excel.
Now I'm fairly new to VBA, slowly getting used to using it, have written some code to transfer one of the calculated tables from Access to Excel:
Option Explicit
Public Const DataLocation As String = "C:\Documents and Settings\Alice\Desktop\Database\TestDatabase21.accdb"
Sub Market_Update()
Call ImportFromAccessTable(DataLocation, "Final_Table", Worksheets(2).Range("A5"))
End Sub
Sub ImportFromAccessTable(DBFullName As String, TableName As String, TargetRange As Range)
Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer
Set TargetRange = TargetRange.Cells(1, 1)
' open the database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";"
Set rs = New ADODB.Recordset
With rs
' open the recordset
' .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable
' all records
.Open "SELECT * FROM Final_Table", cn, , , adCmdText
' filter records
For intColIndex = 0 To rs.Fields.count - 1 ' the field names
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Sub Company_Information()
Dim companyName As String
On Error GoTo gotoError
companyName = Application.InputBox(Prompt:="Enter Company Name", _
Title:="Company Name", Type:=2)
Exit Sub 'Don't execute errorhandler at end of routine
gotoError:
MsgBox "An error has occurred"
End Sub
The above code works fine and pulls up the desired calculated table and places it in the right cells in Excel.
I've got two problems that I'm having trouble with; firstly I have some cell-formatting already done for the cells where the data is going to be pasted into in Excel; I want it to apply the formatting to the values as soon as they are pasted in Excel.
Secondly; I have an add-on for Excel which updates some daily Stock Market values; these values need to be transferred into Access at the end of each working day, to keep the database maintained, I tried some code but have been having some problems with it running.
The code for this part can be seen following:
Sub UPDATE()
Dim cnt As ADODB.Connection
Dim stSQL As String, stCon As String, DataLocation As String
Dim stSQL2 As String
'database path - currently same as this workbook
DataLocation = ThisWorkbook.Path & DataLocation
stCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DataLocation & ";"
'SQL code for GL Insert to Access
stSQL = "INSERT INTO Historical_Stock_Data SELECT * FROM [Portfolio] IN '" _
& ThisWorkbook.FullName & "' 'Excel 8.0;'"
'set connection variable
Set cnt = New ADODB.Connection
'open connection to Access db and run the SQL
With cnt
.Open stCon
.CursorLocation = adUseServer
.Execute (stSQL)
End With
'close connection
cnt.Close
'release object from memory
Set cnt = Nothing
End Sub
I get the following error with this.
Run-time Error '-2147467259 (80004005)'
The Microsoft Jet database engine cannot open the file 'Cocuments and Settings\Alice\Desktop\Database'. It is already opened exclusively by another user or you need permission to view its data.
I'm fairly new to databases, VBA and Access so any help would be greatly appreciated.
Also I have been told that the above method of having an Excel front-end and Access back-end is not recommended but alot of the analysis they conduct is done through Excel, and the charts feature in Excel is much better than Access in my experience atleast; and that is also one of the requirements for this project.
Thank you advance!
Solution to your first problem:
Sorry to be the bearer of bad news, but your entire first module is unnecessary. Instead, try:
Go to Data->Import External Data->Import Data, select your Access file, select your table, and presto! done!
Right-click on your new "External Data Range" to see a number of options, some related to formatting. You can even keep the original cell formatting and just update the values. I do this all the time.
To update the Excel data table later, there is a "External Data Range" toolbar that allows you to refresh it as well as a "refresh all" option to refresh every table in the Excel file. (You can also automate this thru code. It'll take some trial and error, but you're definitely up to the task)
Regarding your second problem
I've never used it, but there is also a "New Web Query" option in there as well. I assume it can be manipulated and updated the same way.
And lastly
Your choice of the Excel front-end and the Access back-end sounds good for your needs. It gets the data to your analysts in a medium they are familiar with (Excel) while keeping the calculations out of the way in Access. Technically, you could try putting all your calculations in Excel, but that might the Excel file much bigger and slower to open.
Do the data entry/updating/reviewing in Access. One of Access' strengths is using forms that allow you to update the tables without any code. Then allow the users to easily export the data to Excel such as by clicking on some command buttons.
Modules: Sample Excel Automation - cell by cell which is slow
Modules: Transferring Records to Excel with Automation
nothing wrong in principle with the excel/access pairing. I'm not familiar with ADO (I use DAO), but your error message seems to be indicating that the path to the datasource is not fully formed; or you already have it opened and hence are locking it.