我正在用Microsoft Excel编写一个宏,该宏在本地SQL Server数据库的表中进行更新,但是我的连接字符串有问题:
sConnect = "Driver={SQL Server};Data Source=(localdb)\MSSQLLocalDB;Database=Scrap;"
但是当我运行宏时,出现此错误:
找不到数据源名称,也没有默认的驱动程序
写连接字符串的正确方法是什么?
答案 0 :(得分:0)
好的,这应该很简单。请参阅下面的链接。
https://www.erpsoftwareblog.com/2017/01/microsoft-excel-connections-sql-databases/
也请检查一下。
https://www.connectionstrings.com/sql-server/
最后,要使用Excel / VBA代码更新SQL Server表,请执行以下操作。
Sub UpdateMyTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim rngName As Range
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=MyDB;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
uSQL = "UPDATE MyTable SET Field = 1 WHERE Field = ' " & rngName & " ' "
'Debug.Print (uSQL)
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
如果此代码有问题,请发回详细信息。谢谢。