Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

(80% Discount Ends Soon!)

ODBC Connections from Excel

I have an access database that I would like to put a DATE into a cell and
have it auto run a query with that date criteria. I have done this with the
query wizard and manualy but would like to automate the process by just
typing the date and pressing the enter any one who could lead me in the
right direction or who has done this before I would appreciate the help
thank you TR

I have an Excel 2000 sheet based on a MS Query to a SQL Server 2000 database.
When I refresh the query, the ODBC connection fails with this error:

SQLState: '01000'
SQL Server Error: 11001
[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets][ConnectionOpen
Connection failed:
SQLState: '08001'
SQL Server Error: 6
[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]Specified SQL Server not

An Access database with links to this SQL Server data source works just
fine. I tested the ODBC connection and it works fine.

The problem cropped up after the database and Excel sheets were moved to a
new physical server.

I tried to edit the Query in hopes of recreating it from scratch but I can't
see the Query because the ODBC error appears and won't open the query editor.
How can I fix the error or open the query so I can manually recreate it?



I have an excel sheet that I have MS Query attatched to. Recently, our servers were renamed to something different. I have changed my ODBC connections on my computer and updated my other excel sheets to point to the correct server via Script Editor, however, on one particular spreadsheet, the script editor is disabled and I can't update the path.\\trap-true, etc.

How can I tell this worksheet to point to the new server? There has to be something in the background where I can tell it to go.

BTW.....I've tried opening the Query and because the new server is down, it will not connect to allow me to cut and paste the SQL code to another worksheet.

Please help

Is there anybody know how to extract data from Oracle RDBMS to a Excel worksheet using VBA. Is it possible to create a db connection & a query in VBA code? Please advise. Thanks in advance.


I have created an ODBC link into an SQL server using the Import External Data
function in Excel 2003. The data is coming through without any problems
except that there is too much of it. Excel has a limit of 65,000 lines and
there is around 300,000 lines of data trying to get through, and the data I
want is at the bottom.

I want to put a filter on one of the columns in the table but don't know
how. I can see the Edit Query box but i've never really used SQL before.

Can anybody help?

When I use ODBC to import data into Excel, all numbers come through with a
leading apostrophe so that Excel sees them as text.
e..g INSERT INTO [Sheet1$] VALUES (10) will come into Excel as '10

I have an excel workbook containing many sheets, of which I wish to export
the data residing on one worksheet only. I would like to know how to do 2
1) export the data into an email so that it appears as flat text, not an
embedded picture, so that I am able to have a robot scrape the data to go
into an HTML ODBC. There will be approx 6 columns by 60 lines and the
workbook has many macros embedded in it.
2) export the data directly into an HTML ODBC
I am not a developer, but asking the questions for one, so appreciate layman
terms if possible, but happy to accept any and all help.

I have set up an ODBC connection via the Admin tools under control panel and it connects fine.

However, when I try to use the same connection to update from Excel, I receive the error ORA-12154: TNS: could not resolve the connect identifier specified.

I have validated that the tnsnames.ora file is in my current path.

I'm using the Oracle in instantclient10_2 driver to create the ODBC Data Source.

Any help would be SOOOO appreciated!


My code executes a query from an oracle db. Everytime I try to run it, it asks for the ODBC password. I was wondering if it's possible to embed the password in the code so it doesn't ask for it. Below is my attempt from piecing together what I found through googling, but does not seem to work. any help would be appreciated, thanks.


   Dim SQLStr As String
   Dim connection As ADODB.connection
   Dim rst As ADODB.Recordset
   Dim intRow As Integer

   SQLStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Range("DBPath") & ";Persist Security Info=False;" & _
                "Jet OLEDB:Database Password='kchu_6789';"
   Set connection = New ADODB.connection
   connection.Open SQLStr
   Set rst = New ADODB.Recordset

Hello guys,

I have a problem for which I can not find a solution within the net.

I have an excel file that uses MSQuery to extract data from other excel files and a VBA that updates all the queries automatically when the file is opened. It works just perfect but the problem is that if I try to open the file from different computers I get the "ODBC Excel Driver login failed"

I have installed all add-ins on each computer and they all have one and the same version of excel.

Could anybody advise what the problem could be?

Thanks a lot!


I have managed to export my SQL db to excel using the mysql ODBC driver but is there any way for me to update mySQL database using the ODBC driver?


I have a spreadsheet connected to our in house system via ODBC. When I refresh sheet2(data) I need sheet1(summary) - which is a pivot table using the data from sheet2(data) to update as well.

Any help on how I could achieve would be great.

Many thanks

Jon D

I download a table from SAGE accounts package using an ODBC link and MSQuery.
I have a series of additional columns in which I manipulate the linked data in various ways.
At some later time I need to refresh the link. Typicaly this will add some new data, relink some existing data and some of the existing data will no longer meet the criteria of the Query and will "drop off". I need to preserve the manipulation of the retained "old" data and have some flag to tell the program that the "new" data needs to be manipulated.

An initial download brings about 300 records. Each refresh adds about 30 and drops off about 30 records.
I thought that this would be easy, but the refresh seems to destroy the row and column relationships so I get spurious results.
can anyone help me with this please?
John Southern


I have a workbook that I created to import any table on our SQL server via ODBC and once I am done with table I completely clear the worksheet to it's original state (as if I just inserted a brand new sheet) and before I import another table, I would like to be able to loop through all the existing connections and delete them. I attempted this with the code below, however I don't really know how to work with the ODBC object model.


Sub DeleteConnections()
Dim Conn As ODBCConnection
For Each Conn In ThisWorkbook.Connections
      'Not sure what to put here. 
Next Conn
End Sub

Please HELP!!!


I have an Excel spreadsheet linked through to a sql table via and ODBC connection and I have a macro to refresh the data. I want the macro to first check that the ODBC connection exists before trying to refresh the data. So it would look like:

IF ODBC Connection exists THEN refresh data ELSE return warning message.

becoz when connection cannot be made, its gives me error. and i have to manually press ok button.

Any ideas....?


Adding records to Database getting following error...
Getting error message exact as below

 '-2147467259 (80004005)': [Microsoft]  
 [ODBC Microsoft Access driver] not a valid password  

Actual Code: error on BLUE line below.

I would really appriciate any help. Just stucked just dont know how to proceed...just same error already asked by someone too but doesnt solve me problem.


 Sub CallAddTransfer() 
   ' Used to call the code from page 480 
   Dim WS As Worksheet 
   Dim Qty As Integer 
   Set WS = Worksheets("AddRecords") 
   FinalRow = WS.Cells(Rows.Count, 1).End(xlUp).Row 
   Ctr = 0 
   For i = 7 To FinalRow 
       Style = Cells(i, 1).Value 
       FromStore = Cells(i, 2).Value 
       ToStore = Cells(i, 3).Value 
       Qty = Cells(i, 4).Value 
       Ctr = Ctr + 1 
       Application.StatusBar = "Adding Record " & Ctr 
       AddTransfer Style, FromStore, ToStore, Qty 
   Next i 
   Application.StatusBar = False 
   MsgBox Ctr & " records added." 
 End Sub 
 Sub AddTransfer(Style As Variant, FromStore As Variant, ToStore As Variant, Qty As Integer) 
   ' Page 480 
   Dim cnn As ADODB.Connection 
   Dim rst As ADODB.Recordset 
   Dim pwd As String 
   MyConn = ThisWorkbook.Path & Application.PathSeparator & "Transfers.mdb" 
   MyConn = "Driver=Microsoft Access Driver (*.mdb);DBQ=" & MyConn 
   pwd = "mypass" 
   ' open the connection 
   Set cnn = New ADODB.Connection 
   With cnn 
       '.Provider = "Microsoft.Jet.OLEDB.4.0" 
        .Open MyConn, mypass  
   End With 
   ' Define the Recordset 
   Set rst = New ADODB.Recordset 
   rst.CursorLocation = adUseServer 
   ' open the table 
   rst.Open Source:="tblTransfer", _ 
   ActiveConnection:=cnn, _ 
   CursorType:=adOpenDynamic, _ 
   LockType:=adLockOptimistic, _ 
   ' Add a record 
   ' Set up the values for the fields. The first four fields 
   ' are passed from the calling userform. The date field 
   ' is filled with the current date. 
   rst("Style") = Style 
   rst("FromStore") = FromStore 
   rst("ToStore") = ToStore 
   rst("Qty") = Qty 
   rst("tDate") = Date 
   rst("Sent") = False 
   rst("Receive") = False 
   ' Write the values to this record 
   ' Close 
 End Sub 

The code is from Bill's Latest book i guess .

Thanks again


Wondering if is it possible to populate a combobox with values from a single column sql query.

1: I do not want to have the recordset returned to a query table and then have combobox populate from query table (trying to cut out the "middleman")
2: I have odbc connections only, I do not have the privledges to add on the ADO add-ons, and if I can get it, my clients will not have it.

The connectionstring I use is this

Dim varconnection As String
        varconnection = "ODBC;DRIVER={SQL Server};Server=MyServer;DATABASE=MyDatabase;UID=that dude;PWD=password"

Any help would be greatly appreciated

I like to connect to a SQL 2005 database from my Excel VBA project.

I have setup a ODBC data source called MSSQLDEV that connects to the SQL 2005 database

How do I build the connection string using this ODBC data source to connect to the SQL 2005?

Alright, I've setup a little macro in excel based on VBA code which runs a query against a MySQL database. This setup has been working great for us without any problems until now.

It seems the SQL query I'm trying to run is breaking QueryTables somehow. This query I'm trying to run is complex and involves a "UNION ALL". This SQL query runs perfectly fine in MySQL Query Browser.

However, when I try and run this query using QueryTables.Add and ODBC, some of the columns are not being returned.

Specifically, I have found that the only columns not being returned are ones which do not have matching UNION "Field Types".

aka: On the top part of my UNION, the first column returned is an INT, and on the bottom of my UNION (the second query), the first column is a VARCHAR. For some reason MySQL Query Browser is perfectly okay showing these results, but QueryTables can't handle it, and drops these columns.

ANY help would be VERY APPRECIATED!!

Here is my VBA code:


Sub SQLGetNewData()

Dim sConn As String
Dim sSql As String
Dim sDateFrom As String
Dim sDateTo As String
Dim oQt As QueryTable

'Sets the database connection
sConn = "ODBC;DSN=Database_Name;UID=username;PWD=password"

'get query parameters

'build the query.
' I have not included the original complex SQL query here, and I have created a "VIEW" in MySQL to replicate the query. Because I have created a VIEW, I simply need to query this view just like it's a table.

sSql = "SELECT * from view_revenue "

Worksheets("Query Info").Activate
[B7].Formula = sSql

'clear the data area

'clear existing data connections
For Each oQt In ActiveSheet.QueryTables
Next oQt
If ActiveWorkbook.Connections.Count > 0 Then
    i = 1
    Do While ActiveWorkbook.Connections.Count > 0
        i = i - 1
End If

'get new data
With ActiveSheet.QueryTables.Add(Connection:=sConn, _
        Destination:=Range("A1"), Sql:=sSql)
    .Refresh BackgroundQuery:=False
    .RefreshPeriod = 0
    .RefreshOnFileOpen = False
End With


End Sub

Ok, here is the issue...

I've written an add-in that is used in a couple of locations. In each location, users have an ODBC connection to a database. The name of that ODBC connection is the same at each location.

However, the name of the actual database that it connects to varies...

For instance, in one location it is "Database"

But in another location it is "DATABASE"

The database holds the same information at both locations, but I've found my queries are case sensitive when it comes to establishing a connection.

Right now, I'm getting around it by using an inputbox, bt there has to be a better way...

Is there any way to use VBA to look at an existing ODBC connection and then get the name of the DB from there?

Any help or advice is appreciated.


A query has landed on my desk - which i'm struggling to figure out.

I have an Excel 2007 workbook which pulls data from a shared Access database.

The user has complained that it is not working properly.

To test it I attempted to refresh the connections, and get an error message:

ODBC Microsoft Access Driver Login Failed

Which then continues to say that it cannot find the mdb file. However, the path that it states the file should be in is different to where it is. This was working fine yesterday.

We also had a mandatory service update overnight - would this potentially cause this?

I'm trying to figure out if the file has been moved, whether it is a problem with the ODBC setup (and therefore infrastructure can have a look), or whether I have inadvertently changed something within the database itself (although I have only been creating queries).

Any help would be much appreciated!


I have a file on a netowk that has an ODBC sql feed set up.

When I choose to share the file, the "REFRESH DATA" icon is shaded out - thus meaning the user can not refresh on demand.

Im using excel 2003 is there a route round this?

Hello All,

I have a query table that is refreshed from a sql server. I have the connection string figured out



but, when I try to use it on someone's computer who doesn't have a datasource setup, it prompts them to do so with the ODBC Administrator program. Is there a way I can do this programatically?

user's connection is to a SQL database.

Update: Okay, found out about DSN-less connections currently using

varConnection = "ODBC;DRIVER={SQL Server};Server=myserver;DATABASE=mydatabase;UID=me;PWD=mypassword"

However, the "Select Datasource" window still crops up. How do I set up the connect to avoid any prompts to "select Datasource" as that is a manual, technical process

Update: for servername, had to specify ip address as some end users were accessing remotely.


I was wondering if it was possible to have more than one SQL statement off one ODBC Connection?

And if the answer is 'Yes' how?

Many Thanks


I'm working with this Access 2000 database and am trying to export some information but continue to get the following error after I select the location to save...

Run-time error 3146 ODBC --call failed
When I attempt to debug the error it's high-lighting the following code...

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "TargSO", strFolderName & ("\Open_Sales") & Format(Date, "yymmdd") & "-" & Format(Time, "hhnn") & ".xls", True
MsgBox ("File Created!")

could anyone shed some light on whats going on or point me in the right direction?

any help would be muchly appreciated - thanks in advance.

Hi Folks:

I have a VBA script that communicates with Oracle - when I click on the refresh button, a dialog box pops up and asks for the Server Name .... I was wondering if I can pass this variable to the connection instead of having the users have to enter it each time - the problem is that they likely don't even know what the server name is.



Query is below:

If global_username = "" Then Call password_entry

strConOracle = "Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP) "
strConOracle = strConOracle & "(HOST=" & HOST & ")(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=" & DBNAME
strConOracle = strConOracle & " ))); uid=" & ORACLE_USER_NAME & " ;pwd=" & ORACLE_PASSWORD & ";"

Set oConOracle = CreateObject("ADODB.Connection")
qstr = " Select * from query_result "

oConOracle.Open strConOracle

splitsql = SplitString(qstr)

' On Error Resume Next

With ActiveWorkbook.PivotCaches.Add(SourceType:=xlExternal)
.Connection = "OLEDB;" & oConOracle
.CommandType = xlCmdSql
.CommandText = splitsql
.CreatePivotTable TableDestination:= _
"'[ABCHAMP_resp_prof_JUL10 v17.xls]MainMenu'!R23C3", TableName:="PivotTable1", _
End With

Running the macro recorder I got this:


With ActiveWorkbook.Connections("YearBS").ODBCConnection
.BackgroundQuery = False
.CommandText = Array( _
"sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
, "SummarizeColumnsBy = 'Month'")
.CommandType = xlCmdSql
.Connection = Array(Array( _
"ODBC;DSN=QuickBooks Data;DFQ=I:\ACCOUNTING\test.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC " _
), Array( _
"Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
.RefreshOnFileOpen = False
.SavePassword = False
.SourceConnectionFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
End With

Now I want the 2 YEARS to be able to change based on cell data... Or if it helps the 2 cells are just This Year and last year (ie. NOW() and NOW()-365 but formatted as custom = YYYY)

So I have this, but it seems to throw me an error everytime I try it:

 With ActiveWorkbook.Connections("YearBS").ODBCConnection
        .BackgroundQuery = False
        .CommandText = Array("sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'")
        .CommandType = xlCmdSql
        .Connection = Array(Array( _
        "ODBC;DSN=QuickBooks Data;DFQ=I:\ACCOUNTING\test.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC " _
        ), Array( _
        "Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With

The error I get now in Microsoft VB is

Run-time error '1004':
Application-defined or object-defined error

I also tried changing

.CommandText = Array("sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'")


.CommandText = Array( GetSQLString() )

after making

Public Function GetSQLString()
    GetSQLString = "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'"
End Function

I also tried

.CommandText = Array(Sheet3.Range(D10))

after setting D10 on sheet3 to =GetSQLString()

Thanks for your help!

I have created a system DSN to an SQL Database programmatically and would like to test the database connection via a command button before executing any queries against the database.

Can anyone help me write this?

I need to create a database query within execl so I can update my excel sheet directly from a ms project source file.

Background story - currently have a massive programme plan. We also have an excel sheet which contains an extract of all the milestones from the programme plan. The excel sheet is updated on a weekly basis - updates made on RAG status, milestone end date and % complete. We are using a 'milestone code' to reference from excel to project. Because its a manual process of checking each individual milestone in the programme plan (140 milestones) its a long and tiresome process.

I was thinking that if we could automate this using an ODBC connection so it updates the data automatically it would cut down an hours work to the click of a button. So basically I was just wanting to know if that is possible. If not, are there any other suggestions to update the information automatically.

Thanks in advance.

P.S. I have attached a picture of a sample spreadsheet and project file as a reference. Hopefully it should give people an idea of what they look like and what Im trying to achieve.

Alright I have an existing data connection to an ODBC data source. I am curious how I can modify one of the query parameters programatically.

So for instance, my data connection properties which already has a connection setup includes this statement.statement:

SELECT "DataTable"."User Name"
FROM "DataTable" "DataTable"
WHERE ("DataTable"."Office Location"= 'Dallas TX')

And I can refresh this query via VBA with Activeworkbook.RefreshAll or something similiar.

My question is, is there any way to programmatically change the queries parameter on the fly?

So I would like to define a variable called "Location" and then insert that into the Office Location part of the query...

I think if someone could help me get my data connection completely into VBA, instead of on the Data Connections tab, I could probably figure it out myself.



We regularly develop queries from Excel via MS query to an SQL Server 2005 database.

We have had issues where if an Alias is used in the SQl Database and the Alias contains spaces MS query complains to the effect 'Incorrect syntax near "whatever". On replacing the spaces with underscores all is well. Now to the point, we developed a spreadsheet using the above connections (even having the alias with spaces) and all was fine. It has now decided to erratically complain with 'incorrect syntax etc." message. Sometimes it will run correctly on my collegues machine but wont run correctly on mine. Strangley enough the client can dial in remotley and run the query fine.

We have SQL server 2005 and excel 2003 and 2007 and run windows xp professional.

Has anyone had this one before?



I am trying to pull data into excel from another program using the ODBC query. This is the code that i have:

WHERE ("BV:CallTracker"."Create-date">={ts '2010-07-05 00:00:00' })

where the date is located is what I am trying to change. I need it to just pull the current date without me having to manually enter it in.


I have this connection which is working fine now. But i like it to be dynamic and picking up the new range from excel. I tried changing the cells in red to fPath but it wouldn't work.

Hope someone can enlighten. Thanks.

Currently, cell E3 read as: C:\DATA\DEMO17_DB.mdb

Sub SQLQuery()

Dim varConnection
Dim varSQL
Dim fPath As String

fPath = Range("E3").Value


varConnection = "ODBC; DSN=MS Access Database; DBQ= C:\DATA\DEMO17_DB.mdb ; Driver{Driver do Microsoft Access(*.mdb)}"


With ActiveSheet.QueryTables.Add(Connection:=varConnection, Destination:=ActiveSheet.Range("A1"))
.CommandText = varSQL
.Refresh BackgroundQuery:=False
End With

End Sub

Hello all,

I'm trying to use a macro to refresh a pivot table obtained thru an ODBC connection. At the same time, i want to change the CommandText field to change the dates i'm using (I only want to get one year of data). I did this by recording the refresh and then changing the CommandText. Here is the code I have at the moment:


    FullString = "V_DATE_ACT>={ts '" + Dinicio + " 00:00:00'}) AND (V_LOGONE_DB.DLV_DATE_ACT

I have a client that has hundreds of spreadsheets that use database queries created within excel (not vb) to link to data stored in a third-party database (Pervasive) via ODBC.

Recently that datbase moved from Drive D: to Drive E:. I updated the ODBC connection to reflect the move. Unfortunately, now none of the excel queries work. I get an ODBC connection error.

If I create a brand new query using the same DSN, it works fine. The DSN also works fine in Access and Word.

I guess when the query is stored in Excel, it stores the the data location within the spreadsheet and no longer references the DSN. Is there any way to view or modify this connection short of creating new queries in hundreds of spreadsheets.


I have the same problem!!!


Does anyone no this?


I am using Excel 2007 and Tally 9. I was able to export some master data from Tally into excel using ODBC but am unable to export transactions data

I someone could help me would really appreciate it

I have a spreadsheet that has over 30 ODBC queries to a MS Access database. Via VBA I programmed a command button to do a simple refresh all:


This takes about 30 minutes to complete...it seems to take a long time to Connect to the datasource (based upon the status bar message).

If I change the code to have 30 entries of the code below it takes less than 1 minute:

'A1 is the location of the query table
Selection.QueryTable.Refresh BackgroundQuery:=False

The workaround is worth it from a performance perspective but NOT from a maintenance perspective. Any advice on how to make the ActiveWorkbook.RefreshAll run in a reasonable amount of time.

Please help me before this laptop becomes a Frisbee!

I almost have this working but I'm getting stuck on this error every time I execute it. I have an ODBC with read-only privileges and I recorded part of the code from the macro. The "from" and "to" date fields I added ( I think I'm correct). I would truly appreciate the help.

Here's the code:

Private Sub CommandButton1_Click()
Dim smpldatea As Date
Dim smpldateb As Date

Dim fdate1 As String
Dim fdate2 As String

smpldatea = UserForm1.TextBox1.Text
smpldateb = UserForm1.TextBox2.Text

fdate1 = Format(smpldatea, "m/d/yyyy hh:mm:ss")
fdate2 = Format(smpldateb, "m/d/yyyy hh:mm:ss")



With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
), Array( _
)), Destination:=Range("A1"))
.CommandText = Array( _
, _

I have a client with an excel spreadsheet that is based on several ODBC queries. He is writing a macro to automate the data refresh. He has the username/password for the server coded in the connection string as described on Microsoft's support site: "DSN=; UID=; PWD= ;" and the password is saved in the ODBC connection as well. However, when he runs the Macro to refresh, it still prompts him for the password as it refreshes each query. The username populates correctly but the password field stays blank. Any ideas?


I am modifying the macro in Excel, which was written by my colleague before he quits the company. I have been assigned to continue coding the macro in Excel. The objective of this macro would be " get the required data from a local DB by calling the SQL query and plot the graph based on the data gathered " .

I am quite new to this environment and I am slowly learning the VBA scripts coded by my colleague. When I run the macro, I am getting the Run time error

"Run Time Error 3146 ODBC - call failed". I searched in the internet to resolve this problem, but I couldn't. May be if I am aware of those kind of Excel macros, I could have solved this run time error.

I have pasted below the code

Public FileContents As String 'global variable to contain the SQL query string
Public RowCounter As Integer
Public ColCounter As Integer
Public RowCounter1 As Integer
Public ColCounter1 As Integer
Const FTP_ip = ""

Private Sub CommandButton1_Click()

Dim strDBName As String
Dim strDBUser As String
Dim strDBPwd As String
Dim strDSNName As String
Dim strConnectionStr As String
Dim strQueryFile_path As String 'filepath of SQL Query file
Dim wrkODBC As Workspace
Dim conDb As Connection
Dim rstTemp As Recordset

strDBName = "tpfdb"
strDBUser = "root"
strDBPwd = "admin"
strDSNName = "tpfdatabase"
strQueryFile_path = ThisWorkbook.Path & "\Queries\"

' Create ODBCDirect Workspace object.
Set wrkODBC = CreateWorkspace("NewODBCWorkspace", strDBUser, strDBPwd, dbUseODBC)

' Open read-only Connection object based on information
' you enter in the ODBC Driver Manager dialog box.
strConnectionStr = "ODBC;DATABASE=" + strDBName + ";UID=" + strDBUser + ";PWD=" + strDBPwd + ";DSN=" + strDSNName
Set conDb = wrkODBC.OpenConnection("localdb", dbDriverComplete, False, strConnectionStr)
Set rstTemp = conDb.OpenRecordset("SET GLOBAL sql_mode='ANSI';", dbOpenDynamic)

I am getting the error while executing the command highlighted above. As I said i am new to this environment, can anyone help me to resolve this?

Also it would be great if anyone can give me some reference/websites that tells about ODBC in Excel.

Many Thanks in Advance!!!!!!!!!!





Here is the situation: The company I work for has several Excel spreadsheets that are linked to our SQL Server 2000 database via an Access file. All has worked for years until now. When I try to Refresh the spreadsheet for Company3, I get an ODBC Connection Failed Error. Basically, the configuration is as follows:

SQL Server: Database has 3 tables for each company which we will call respectively - Company1, Company2, Company3.

AccessFile.mdb contains linked tables to those tables.

Excel Spreadsheets have a Microsoft Query defined using a Microsoft Access ODBC driver. From there, the linked table
Company3 and its appropriate columns are selected. (it is interesting to note the connection seems to work as it will show the column names when I click (+) to expand the table.) However, as soon I try to run the query, it fails with a ODBC Connection Error.

+++ Note +++ If I select a SQL Server ODBC driver instead of a Microsoft Access ODBC driver in the Microsoft Query Wizard, it will work fine. Data gets refreshed with no problem.

Here is what I have tried and observed:

1. Tested the OBDC connection through the ODBC Datasource Adminstrator. Works fine.

2. In Microsoft Query, selected SQL Server 2000 ODBC Driver.
Refreshed the Excel Spreadsheet. Works as mentioned above.
(The current configuration worked previously using an Access ODBC Driver to the linked SQL table.)

3. Created a new Access database with a link to Company3, thinking maybe the mdb file is corrupt. Still didn't work.

4. I created a new Excel spreadsheet and Microsoft Query to
to the linked table. Same results.

5. Compared the datatypes for Company3 against Company1 and Company2. Looked ok.

6. Copied Company3 into a test table. Tried Refreshing the Excel spreadsheet with Access ODBC Driver and the test table (all records). ODBC Connection failed. I even tried deleting all but one record in the table, but I obtained the same results.

7. Tried SQL Profiler to see if could give any useful information why the conncection failed. All I could find that it was testing the connection, but I could find any information why it failed.

9. Turned on ODBC tracing. Here is a snapshot of the log file:

msqry32 580-eb0 ENTER SQLDriverConnectW
HDBC 00892BD0
HWND 00000000
WCHAR * 0x74329A38 [ -3] "******\ 0"
WCHAR * 0x74329A38
SWORD * 0x00000000

msqry32 580-eb0 EXIT SQLDriverConnectW with return code -1 (SQL_ERROR)
HDBC 00892BD0
HWND 00000000
WCHAR * 0x74329A38 [ -3] "******\ 0"
WCHAR * 0x74329A38
SWORD * 0x00000000

DIAG [IM006] [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed (0)

DIAG [IM008] [Microsoft][ODBC SQL Server Driver]Dialog failed (0)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417260
SWORD 4095
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 0 (SQL_SUCCESS)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4 (0)
WCHAR * 0x02417260 [ 66] "[Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed"
SWORD 4095
SWORD * 0x0012D4C0 (66)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x024172F6
SWORD 4020
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 0 (SQL_SUCCESS)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4 (0)
WCHAR * 0x024172F6 [ 48] "[Microsoft][ODBC SQL Server Driver]Dialog failed"
SWORD 4020
SWORD * 0x0012D4C0 (48)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417368
SWORD 3963
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 100 (SQL_NO_DATA_FOUND)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417368
SWORD 3963
SWORD * 0x0012D4C0

msqry32 580-eb0 ENTER SQLFreeConnect
HDBC 00892BD0

msqry32 580-eb0 EXIT SQLFreeConnect with return code 0 (SQL_SUCCESS)
HDBC 00892BD0

msqry32 580-eb0 EXIT SQLExecute with return code -1 (SQL_ERROR)
HSTMT 00891B18

DIAG [S1000] [Microsoft][ODBC Microsoft Access Driver] ODBC--connection to 'CompanyDatabase' failed. (-2001)

Not sure what is causing this error. I am leaning that it has to so some thing with the table (Company3) itself. Permissions? Any assistance on issue would be greatly appreciated.:-)

By the way, does anyone know why sometimes you get a login dialog when you open a datasource and sometimes not?

I wish to import a Oracle table via a macro and have done it via the wizzard and recorded that. when i run it i get a 1004 error at the refresh. I then scripted it myself and it fails at the connect line. Can you help me please. I got the driver from a record macro script...

My script:

Dim oConn As Object, oRS As Object
Password = InputBox("input password", "enter password")
Set oConn = CreateObject("ADODB.Connection")
oConn.Open "Driver={Oracle ODBC Driver};" & _
"Dbq=RPTCCB;" & _
"Uid=JSHAPER;" & _
"Pwd=" & Password

Set oRS = CreateObject("ADODB.RecordSet")

Range("A1").CopyFromRecordset oRS

Thank you in advance to anyone that spends any time helping me figure this out...

I have a SQL query (through an ODBC connection) that populates an Excel spreadsheet. The thing is that I want add a criteria "WHERE x = [cell reference]". I know this question has been asked repeatedly in different forms but it seems that connecting with Excel 2007 through an ODBC connection doesn't behave the way others do. I've tried using the following syntax:

WHERE A.EMPLID = '" & Range("B1") & "'

A.EMPLID is my SQL field name
B1 is the cell where I enter my A.EMPLID filter value

If I manually edit the query (as below) it returns a perfect set of data. I'm just trying to avoid having to manually edit the query every time I want a new data set.

WHERE A.EMPLID = '81726354'

The query with the cell reference doesn't cause any errors but it doesn't return any results either. I've also named the cell as a range but don't know how I'd reference that in a SQL query (if that's even possible). I'm trying to avoid doing it with VBA.

I have had this message pop up on a workbook that has been running flawlessly for monthe. The table goes to an Access book and queries a table and imports the reuslts. And suddenly today I am getting this message. Does anyone know what it means?

[Microsoft] [ODBC Access Driver] Too few parameters: Expected 1

Hi All,

I need your help. Could you please provide me a sample code which will allow me to connect to Oracle 10g Database and get some rows out of it. I want to do it without using ODBC


I am trying to change the SQL command to an odbc database connection

Sub Macro1()
' Macro1 Macro
    With ActiveWorkbook.Connections("YearBS").ODBCConnection
        .BackgroundQuery = False
        .CommandText = Array( _
        "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
        , "SummarizeColumnsBy = 'Month'")
        .CommandType = xlCmdSql
        .Connection = Array(Array( _
        "ODBC;DSN=QuickBooks Data;DFQ=I:\ACCOUNTING\Quickbooks\Red Tail Networks, Inc.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC " _
        ), Array( _
        "Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With
    With ActiveWorkbook.Connections("YearBS")
        .Name = "YearBS"
        .Description = ""
    End With
End Sub

I recorded that in excel and then when I try to run it I get an error of:
When I debug it highlights this line:

        .CommandText = Array( _
        "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
        , "SummarizeColumnsBy = 'Month'")

Any help would be appreciated thank you.

Now I also found this:

which makes it out to be a bug in excel and that I need to change the type of connection, then change the string, then change the type of connection back. I am not really sure how to do this but below is the post that seems important from the link above:


I wrote the following functions which I call right before and after I update the CommandText.

Private Sub dbODBCtoOLEDB()
Dim pcPivotCache As PivotCache
Dim strConnection As String
For Each pcPivotCache In ActiveWorkbook.PivotCaches
If pcPivotCache.QueryType = xlODBCQuery Then
strConnection = _
Replace(pcPivotCache.Connection, "ODBC;DSN", "OLEDB;DSN", 1, 1, vbTextCompare)
pcPivotCache.Connection = strConnection
End If
Next pcPivotCache
End Sub

Private Sub dbOLEDBtoODBC()
Dim pcPivotCache As PivotCache
Dim strConnection As String
For Each pcPivotCache In ActiveWorkbook.PivotCaches
If pcPivotCache.QueryType = xlOLEDBQuery Then
strConnection = _
Replace(pcPivotCache.Connection, "OLEDB;DSN", "ODBC;DSN", 1, 1, vbTextCompare)
pcPivotCache.Connection = strConnection
End If
Next pcPivotCache
End Sub

If anyone could help me adapt this to my connection that would be incredible. It is important to note I will be running this 3 times to change seperate pivot tables and that I also have other pivot tables that connect to a different database that I do not need changed. Thanks!

Hey Guys,

I have an access database as a store for some data. I have a custom function in my MDB that is basically a CASE statement. It works when build queries within the MDB itself...is there a way I can call on this function when querying the tables externally via an access ODBC connection?

I am using microsoft query to pull the data into excel.



I just started working with access and I am getting this error every two queries that I run. What I need to do is close Access and start it again and then I get to run two more queries and it crashes again.

I dont know why this is happening but obviously something it wrong. I Googled it and could not find an answer.

The error message I get is:

ODBC--call failed.
[MySQL][ODBC 5.1 Driver]....-highperf-b13-log]MySQL server has gone away (#2006)

Does anyone know why this is happening and what I can do to fix it?

Please let me know.

- Lior

Currently I have an excel 2007 spreadheeet with around 400 columns of data, I was then hoping to make an ODBC connection to this from a worksheet on a second spreadsheet. Unfortunately only 250 odd columns are actually being recognised using this ODBC link, is there a way around this?