从Excel VBA更新SQL Server表

我试图使用下面的代码来获取活动单元格,并更新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我已经设置并打开了代码中的logging集,为什么它会被closures?

我需要做什么来纠正这个问题,并让活动单元格填充查询和更新SQL Server中的表?

这下面是我曾经能够更新SQL Server中的表的代码,这只是我想要的。 它需要activecell和更新。

 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