我在我的PC上安装了SQL Server 2008,并且我正在编写VBA代码来填充该数据库上的表。我能够将来自各种在线资源的以下代码拼接在一起:
Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
Dim sql_pass As String
'Create the connection string
strSRV = ".\SQLEXPRESS"
strDB = "backend"
sql_login = "asd"
sql_pass = "asd"
strConn = "Provider=SQLNCLI10" & _
"Server=" & strSRV & ";" & _
"Database=" & strDB & ";" & _
"Uid=" & sql_login & ";" & _
"Pwd=" & sql_pass & ";"
'Create the Connection and Recordset objects
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute
conn.Open strConn
Set rs = conn.Execute("SELECT * FROM *;")
'Check we have data
If Not rs.EOF Then
'Transfer result
Sheets(1).Range("A1").CopyFromRecordset rs
'Close Recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
'Clean up
If CBool(conn.State And adStateopen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
目前我收到错误:
无法找到提供商
从在线研究中我发现它可能是由于ODBC配置,所以我去了ODBC数据源管理员。定义了3个用户数据源:dBASE文件,Excel文件和MS Access数据库。我为SQL Server Native Client 10.0添加了第三个。
我无法在connectionstrings.com
找到答案,这似乎是一个受欢迎的参考。我收到错误的原因是什么?我怎样才能解决这个问题呢?有一次,我的VBA将指向远程服务器,因此我不希望该解决方案成为本地解决方法。
答案 0 :(得分:4)
看起来你的strConn缺少一个分号...尝试这个,看看是否有什么不同: -
strConn = "Provider=SQLNCLI10;" & _
"Server=" & strSRV & ";" & _
"Database=" & strDB & ";" & _
"Uid=" & sql_login & ";" & _
"Pwd=" & sql_pass & ";"