从Excel VBA更新SQL Server表

问题描述 投票:2回答:2

我正在尝试使用下面的代码来获取活动单元格并更新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中的表?

excel vba excel-vba
2个回答
4
投票

这是我以前能够在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

0
投票

希望此文件将使您将数据更新到sql server

我使用了2012 sql服务器,数据库名称为ajayzori,表名称为allproduct

xlsm的链接。

https://drive.google.com/file/d/11ct2keEqa5__4aWL96xj0DTfhSbRBmha/view?usp=sharing

© www.soinside.com 2019 - 2024. All rights reserved.