Setting an ODBC connection string in VBA

40,901

In your VBA code, add ODBC; to the beginning of your new connection string.

.Connection = "ODBC;SERVER=myserveraddress;UID=SYSTEM;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=SYSTEM;DATABASE=myDBname;"
Share:
40,901
CactusCake
Author by

CactusCake

I work mostly in Transact SQL - fixing up individual records when applications are running into errors, identifying why those errors are occurring so the underlying application code can be fixed, and maintaining Stored Procedures. In my spare time I like to play around with Java. I've made a couple of games for Android to get myself familiar with Object Oriented programming, but nothing too serious, plenty of trial and error. I like to build "real" things too, so I dabble in Arduino; the cats appreciate their WiFi enabled feeder when I'm out of town. I also keep bees, so there's that.

Updated on January 30, 2020

Comments

  • CactusCake
    CactusCake over 4 years

    I have created a macro that sends a new CommandText to an ODBC Connection in my Excel spreadsheet and then refreshes the table of results associated with the query. This has been working fine, but I've noticed that each time I run the macro it overwrites the connection string with some default values that work on my machine but will not work on other users' machines because they do not have the saved connection file that I have. The more specific connection string that specifies a server address works when entered manually, but will get overwritten anytime the macro is run.

    I figured I would just have the macro write the connection string at the same time it sends the new CommandText, but I'm running into errors.

    My code is as follows:

    Sub NewData()
    
    Dim lStr As String
    lStr = ""
    lStr = lStr & " USE myDBname; "
    lStr = lStr & " WITH X AS ("
    lStr = lStr & " SELECT"
    lStr = lStr & " column1, column2, column3, etc"
    lStr = lStr & " FROM"
    lStr = lStr & " etc. etc. etc."
    
    With ActiveWorkbook.Connections("PayoffQuery").ODBCConnection
    
    .CommandText = lStr
    .Connection = "SERVER=myserveraddress;UID=SYSTEM;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=SYSTEM;DATABASE=myDBname;"
    
    End With
    
    End Sub
    

    The .CommandText still updates just fine, but the .Connection throws runtime error 1004: Application-defined or object-defined error.

    Any idea what I'm doing wrong here? TIA.

  • CactusCake
    CactusCake over 9 years
    Thanks, it worked! Interestingly, that part does not show up in the connection properties window after running the macro. But it must have an impact because it does not work if that part is omitted.