Unable to run Access query through ADODB connection in Excel - excel

I am trying to paste in the results of an access query to a sheet in Excel.
When I run the following code, nothing happens. No errors or warnings, just nothing ever gets pasted in. However, when I run the same code, but use a table instead of a query name, it successfully pulls in the table. But when I replace it with a query name, it returns nothing.
In the past I have done the same thing but instead of calling the query name, I have stored the SQL query as a string within the macro and called the query by referencing the string. I tried that and that did not work in this case.
The query I am trying to pull references other queries as tables, and I think this is why I am having issues. Like I said, I have pulled data from Access with this code many times before but have only been able to do so when I am referencing tables only, and not queries.
Dim Con As ADODB.Connection
Set Con = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim iCols As Integer
Set Con = New ADODB.Connection
With Con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open AccessDBPath
End With
Set rs = New ADODB.Recordset
rs.Open "query1", Con
Sheets("NAHV").Range("E2").CopyFromRecordset rs
I have tried replacing the rs.Open line with the Execute command:
Set rs = Con.Execute("query1")
and this also did not work.
I have also tried replacing the full block with
Dim cn As Object, rs As Object
Dim myFile As String: myFile = AccessDBPath
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & myFile & ";"
.Open
End With
Set rs = cn.Execute("query1")
Sheets("NAHV").Range("E2").CopyFromRecordset rs
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
and this did not work either.

Related

ODBC connection failed error in Excel 64-bit

I have a linked table in ms-access which is linked to a sql server table, and when I am trying to fetch the data in excel via VBA from ms-access linked table the error message "ODBC connection failed" showing.
Note:- I am manually successfully able to refresh ms-access linked table in ms-access, "peoplemain" is the name of linked table.
Note:- When I tried to fetch data from non linked table, it is running successfully.
Below code is working in Excel-32 bit version, but not working in excel-64 bit.
[code]
Sub FetchData()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim conn As String
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\SampleforPractice.accdb;"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open conn
rs.Open "Select * from peoplemain", cn 'Error Line
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Thanks
Kashif
I would try out setting a strSQL as a string like this (I had the same issue you did and when I made the change it worked for me):
Sub FetchData()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim conn As String, strSQL AS String
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\SampleforPractice.accdb;"
strSQL = "Select * from peoplemain"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open conn
rs.Open strSQL , cn 'Error Line
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

Performance issue with access to excel vba

I need to get data from Access to excel vba, I use ADODB.
My problem is that although the database is relatively small and query results 30-40 records only, the process gets stuck either with the ".open" or with "copyfromrecordset" line and takes 40-50 secs to display the records.
This is my code.
I made some tests with different cursor types and locktypes with no result. The query is working executed directly from access and I have no issue when the connection points locally to my PC. I am on office 365. I referenced the activex data objects 2.8 library.
Sub loadTestDisplay2()
Dim myConnectiom As ADODB.Connection
Dim myRS As ADODB.Recordset
Const conStringNet As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ourserver-f04\COE-Shared\Data Tool\Access\adsLoadTest.accdb; Persist Security Info=False;"
Dim sql As String
sql = "SELECT * FROM tblLoad where user is Null"
Set myConnection = New ADODB.Connection
Set myRS = New ADODB.Recordset
myConnection.ConnectionString = conStringNet
myConnection.Open
With myRS
.ActiveConnection = conStringNet
.Source = sql
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
Sheets.Add
Range("A2").CopyFromRecordset myRS
myRS.Close
myConnection.Close
End Sub

Excel VBA Executing Access Query that Links to Oracle

Let me start of by saying I am new to both this site as well as VBA so please bear with me. Thank you in advance for your help.
I have a VBA function that runs an existing query from Access. Some of the tables being queried are stored in an Oracle database that require a user specific password access. Right now, a sub that I wrote to automate a report calls this function 7 times and requires the user to input their Oracle password each time the function is called (it also stops the sub and gives an error message if they type in the password incorrectly which I see as a likely event if they need to do it 7 times). The code works but I would like to find a way to have the code ask for the password once and be done with it. All of the solutions I have found involve connecting to and querying Oracle directly which requires very complicated SQL coding that I am by no means capable of writing.
I am also having an issue where the columns show up in the excel sheet in a different order than they do in Access for some of the queries. This seems to be consistent so it isn't to big of a problem but I would like to know how to prevent this to prevent any future issues.
Here is the code for the function I am currently using. Any insight would be greatly appreciated!
Option Explicit
'Single Argument "qryName" as string. Runs access qry and copys recordset to active sheet.
Function AccessQueryPull(qryName As String)
'Declare variables
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
'open the connection to the access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=filePath.accdb;"
'format the command to run the query
Dim cmd As New ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = qryName
cmd.ActiveConnection = cn
'execute the query
Set rs = New ADODB.Recordset
Set rs = cmd.Execute()
'copy data to excel sheet
ActiveSheet.Cells(2, 1).CopyFromRecordset rs
'Cleanup
rs.Close
Set rs = Nothing
The reason you are prompted each time for Oracle credentials is that you create a fresh, new connection to MS Access each time the function is called.
Simply persist the MS Access connection by connecting once in the Sub that calls function and pass connection object as parameter. In this way, any connection error is caught in the parent routine. As for column order simply declare the columns in the needed order in SQL statement.
Sub RunQueries()
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
'open the connection to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=filePath.accdb;"
Call AccessQueryPull(cn, "SELECT Col1, Col2, Col3 FROM Qry1") ' AND OTHER 6 CALLS
cn.Close
Set cn = Nothing
End Sub
Function AccessQueryPull(accConn As ADODB.Connection, qryName As String)
'format the command to run the query
Dim cmd As New ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = qryName
cmd.ActiveConnection = accConn
'execute the query
Set rs = New ADODB.Recordset
Set rs = cmd.Execute()
'copy data to excel sheet
ActiveSheet.Cells(2, 1).CopyFromRecordset rs
'Cleanup
rs.Close
Set rs = Nothing: Set cmd = Nothing
End Function

VBA code to connect to Oracle Data base to run SQL statements

Hi I need to connect my Excel file to run a macro that executes select query.
My sample code is
Sub Button1_Click()
Range("A1").Value = "Hiii!"
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL, strInput As String
strCon = "Provider=MSDAORA.1;User ID=bis5151XXXXXa1;Data Source=canafpi5467qanfo.iaksedafdqwte.com;Password=iXoXXX8886s55it"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strInput = InputBox("Input Desired Name")
Sheet1.Range("B1").Value = strInput
strSQL = "select * from " & strInput & " where rownum<200"
Sheet2.Range("D1").Value = strSQL
'Added the following four lines
Set rs = CreateObject("ADODB.RECORDSET")
rs.activeconnection = cn
rs.Open strSQL
Sheet2.Range("A10").CopyFromRecordset rs
rs.Close
cn.Close
Set cn = Nothing
End Sub
=============================================
But my Database doesnt have an entry in the tnsnames.ora file. I also tried giving tns details as data source but am getting TNS failure error.
Could some one please help me to connect my excel to oracle just to run a select statement so that the value is returned to a particular cell in excel.
FYI I already have my ODBC configured.

Error when running a parameter query from access 2007 in excel vba

I'm trying to run a query in an Access 2007 database from an Excel 2007 VBA script. The Access query has parameters called "Year" and "Month".
I'm trying to get the following code to work:
Sub RunMyQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim stQRY As String
Dim stCon As String
Dim cmd As New ADODB.Command
Dim prmYear As New ADODB.Parameter
Dim prmMonth As New ADODB.Parameter
dbPath = "<PATH_TO_MY_DB>"
stCon = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & dbPath & ";"
cn.Open (stCon)
cn.CursorLocation = adUseClient
Set cmd.ActiveConnection = cn
Set prmYear = cmd.CreateParameter("Year", adNumeric, adParamInput, , 2011)
Set prmMonth = cmd.CreateParameter("Month", adNumeric, adParamInput, , 5)
cmd.Parameters.Append prmYear
cmd.Parameters.Append prmMonth
cmd.CommandText = "SELECT * FROM [Month_Totals]"
cmd.CommandType = adCmdTable
Set rs = cmd.Execute
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
When I run this, the code stops on "cmd.Execute" with
Run-time error '-214217900 (80040e14)':
Syntax error in FROM clause.
What am I getting wrong?
The command text seems simple enough to me. Am I missing something there?
Am I misusing the parameters functionality of ADODB.Command? I don't think that's the problem here, because I've tried running this same script with a non-parametrized query substituted for Month_Totals, and gotten the same error.
I believe The parameters are only for use when you are using a saved query in access. I would solve your problem by moving the parameters into the SQL statment.
Change
"SELECT * FROM [Month_Totals]"
to
"SELECT * FROM [Month_Totals] WHERE Year = 2011 AND Month = 5"
The reason that this is returning an error is that command type is set to adCmdtable, but the command does not reference a table, it references an SQL string, so:
cmd.CommandType = adCmdText
Next, in order to return specific data, you need to include a WHERE clause, with field names in the correct order for the parameters:
cmd.CommandText = "SELECT * FROM [Month_Totals] Where [Year]=? AND [Month]=?"

Resources