Access Database Engine could not find object - object is Excel named range - excel

This is something that has had me going round and round in circles for a while now, essentially all I would like to do is to insert the values of an Excel dynamic range into an Access table.
I have had success in doing this by referencing the range as for example, however to make things a little more self sufficient I would prefer to use a dynamic range.
The code I have is as follows:
Sub ExportDistDatatoSql()
Dim cn As ADODB.Connection
Dim STRQUERY As String
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\uMyDB.accdb;"
.Open
End With
ssql = "INSERT INTO Crude_Prods_DB Select * from [Excel 12.0;HDR=YES;DATABASE=C:\TEST\mysheet.xlsm].[n_range]"
cn.Execute ssql
End Sub
The error I am seeing is attached and I have checked an [n_range] does exist in the workbook.
[error seen when attempting to insert data into access table from excel named range]
Any suggestions would be much appreciated.

I learned this the hard way. A dynamic range is resolved only when Excel runs, thus it doesn't exist when you just read the file.
Only a saved and fixed Named Range can be read by Access.

Related

Excel VBA - how to query Access database using column values as a parameter?

I have an Excel worksheet that has a list of about 1000 Item Numbers in column A on Sheet1. Currently, I import Sheet1 into an Access table named ItemNumbers and run the following query:
SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice
FROM [ItemNumbers] INNER JOIN MyTable ON [ItemNumbers].ItemNumber = MyTable.ItemNumber
ORDER BY MyTable.ItemNumber;
And then I copy/paste the output to Sheet2.
How can I do this in VBA in Excel and put the results in a recordset? I can figure out how to loop through the recordset and put the results in Sheet2. I'm just not sure on the code to run the query.
I have the following so far. It just needs to be modified to use the values in Sheet1 Column A.
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\MyDatabase.accdb"
strSql = "SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice " & _
"FROM MyTable " & _
"WHERE WHERE (((MyTable.ItemNumber)= ??? IS IN Sheet1!A:A ??? )) " & _
"ORDER BY MyTable.ItemNumber;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
Thanks!!!
If I understand right; what you ask is to join a table from Access with a table in Excel (ADODB).
Check this link from SO, and see if it's helpful:
Selecting 2 tables from 2 different databases (ACCESS)
I haven't tried to combine Access and Excel before, but my guess is that it will work for Excel as well.
An alternate way (and that will certainly work):
Run the query without the WHERE clause and store the result in a
recordset;
Store the data from the Excel sheet that you require in a dictionary,
where the ItemNumber (PK?) is the key;
Run through the recordset, and check with the typical dictionary Exists function
if the ItemNumber from each record is available in the dictionary;
If the record is availabe, store the
recordset values in a separate array (or dictionary) that you can
use for further manipulation, (or perform direct actions if that's what you want to do).

Retrieving data from Excel spreadsheet to Excel spreadsheet in a block

Here's my problem :
I want to retrieve data from an Excel XML spreadsheet (*.xlsx) within another Excel spreadsheet without opening it. So I gave a chance to OLEDB with the ACE Provider.
The connection worked and I made what I wanted, by looping through my recordset. But now I want some optimization, i.e. putting my recordset into excel in a block instead of looping through it.
Therefore I made something like this :
Sub RetrieveData()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=Path\File.xlsx; _
Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"""
.Open
Set rs = .Execute("Select * From [Sheet1$]")
'Problem here
Range(Cells(1, 1), Cells(rs.RecordCount, rs.Fields.Count - 1)) = rs
.Close
End With
Exit Sub
The thing here, is that I'm currently dealing with technologies which I don't know much about them and can't find any documentation on them (e.g. Microsoft ACE 12.0 Provider for OLEDB).
Regards.
(And don't even hesitate to correct my poor grammar)
I think this is what you need:
Cells(1,1).CopyFromRecordset rs
Quite simple, don't you think. But put it instead of this line:
Range(Cells(1,1)................ = rs
And remember to remove comment: 'Problem here :)
By the way, data you get in your sheet don't include columns heading. But I hope you'll cope with that separately.

Adding column to worksheet in Excel with OLEDB

Hello
I'm trying to add new column to the Excel worksheet by command
ALTER TABLE [MyTable] ADD COLUMN Field_dest nvarchar
But on execution of the command got exception "Invalid operation"
I tried table name with and without $ at the end , but got the same result
My questions are
1) Is there some wrong in the command above?
2) Is command ALTER table supported for excel table ?
3) Is the alternative way to add column into excel worksheet - preferable via OLEDB ?
Thanks in advance
Alter table will not work, AFAIK, however, you can Create Table or Select Into, which will allow you to create a new sheet. I cannot get this to run against an open sheet.
Dim cn As Object
Dim scn As String
Dim sSQL As String
strFile = "C:\Docs\test.xls"
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
strFile & ";Extended Properties=""Excel 8.0;HDR=Yes;"""
Set cn = CreateObject("ADODB.Connection")
cn.Open scn
''Note that there is no $ on the sheet to be created
sSQL = "SELECT *,'' As NewField INTO [Sheet17] FROM [Sheet4$]"
''Jet data types
sSQL = "CREATE TABLE [Sheet8] (AText text, ANother text)"
cn.Execute sSQL
If you run against an open file, you will get an error to the effect that Sheetn does not exist.
You can use Create Table instead of Alter Table.
Just use your existing table name, then your columns adds to existing sheet
CREATE TABLE [ExistingSheet$] (ID char(255), oldField1 char(255), newField2 char(255))
it's work!

Is it possible to create a VBA QueryTable outer join between a CSV file and a worksheet?

I'm creating an excel workbook to manage my personal finances. My banks provide transaction data in CSV format and I found a way to import that data into excel using a QueryTable (using a "TEXT" connection.)
I'd like to automatically apply transaction category rules to each imported transaction. I have a worksheet with two columns - a string to match against the transaction "details" provided in my bank's CSV file and the category to apply to the matching transactions.
Is it possible to create an outer join between the CSV data and the categories worksheet and dump the resulting table into another worksheet?
For example (SQL pseudocodeish): SELECT csv.date, csv.details, csv.debit, csv.credit, ws.category FROM [csvfile] csv LEFT OUTER JOIN [worksheet] ws ON csv.details ~= ws.details
~= above would be some kind of string match. I can figure out the SQL, my question is really how to combine the CSV file and worksheet in the same QueryTable.
Excel will open CSV files without blinking, but you can use a connection string, if you prefer. It is even possible to write a query that compares an existing worksheet or named range with a text file using an Excel connection. All you need is a little VBA.
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
'Note HDR=Yes, that is, first row contains field names '
'and FMT delimted, ie CSV '
strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Docs\;" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
cn.open strcon
'You would not need delimiters ('') if last field is numeric: '
strSQL="SELECT FieldName1, FieldName2 FROM The.csv " _
& " WHERE LastFieldName='SomeTextValue'"
rs.Open strSQL, cn
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
You can use any suitable Jet SQL queries against the connection, just be careful about case sensitivity. For example, working with a connection to the current workbook:
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
''This is not the best way to refer to the workbook
''you want, but it is very convenient for notes
''It is probably best to use the name of the workbook.
strFile = ActiveWorkbook.FullName
''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * " _
& "FROM [Sheet1$] a " _
& "LEFT JOIN [Text;FMT=Delimited;HDR=Yes;" _
& "DATABASE=C:\Docs].Import.txt b " _
& "ON a.[Id]=b.[Id] "
rs.Open strSQL, cn, 3, 3
''Pick a suitable empty worksheet for the results
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
It is possible to create an OUTER JOIN referencing disparate data sources (csv, Excel, Access, txt, SQL, Oracle, etc) using ISAM Names in an ADO query. The results are held in a recordset that can be published back to Excel or another datasource as desired. Google "SQL ISAM Names" to find my other posts on the topic.
I am sure a little more info would help clear up my confusion but I don't believe it is possible to set up a SQL query against a CSV as Excel will not recognise it as a Data Source.
Have you thought about simply loading the csv into Excel and generating a pivot table/lookups on the data?

Access - Excel Integration

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.

Resources