Setting an ODBC connection string in VBA

自闭症网瘾萝莉.ら 提交于 2019-12-10 14:52:22

问题


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.


回答1:


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;"


来源:https://stackoverflow.com/questions/28219298/setting-an-odbc-connection-string-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!