gpt4 book ai didi

vba - 从 Excel VBA 更新 SQL Server 表

转载 作者:行者123 更新时间:2023-12-04 00:38:29 25 4
gpt4 key购买 nike

我正在尝试使用以下代码获取事件单元格并更新 SQL Server 中的表。

Sub UpdateTable()
Dim rngName As Range
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=Mydb;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
'Debug.Print (rngName)
Set cnn = New ADODB.Connection
Application.ScreenUpdating = False
cnn.Open cnnstr
Set rs = New ADODB.Recordset
uSQL = "UPDATE MyTable SET FieldNameX = 1 WHERE FieldNameY = '" & rngName & "' "
rs.CursorLocation = adUseClient
rs.Open uSQL, cnn, adOpenStatic, adLockOptimistic, adCmdText
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub

单步执行代码时,它会在 rs.close 行运行时出错,表示 Operation is not allowed when the object is closed我已经在代码中设置并打开了记录集,为什么要关闭它?

我需要做什么来纠正问题并让事件单元格填充查询并更新 SQL Server 中的表?

最佳答案

下面是我用来在 SQL Server 中更新表的代码,这正是我想要的。它需要事件单元和更新。

Sub UpdateTable()
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 FieldNameX = 1 WHERE FieldNameY= '" & rngName & "' "
'Debug.Print (uSQL)
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub

关于vba - 从 Excel VBA 更新 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com