2014-03-06 92 views
1

我試圖使用下面的代碼來獲取活動單元格並更新SQL Server中的表。從Excel VBA更新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中的表?

+0

你能確認記錄集rs已成功打開嗎?在即時窗口中嘗試'?rs.recordcount'(使用CTRL_G)。如果錯誤發生在'rs.Open'這一行上,那麼連接可能不會打開。 –

+0

我應該在哪裏放行rs.recordcount?我把它放在我的rs.open行後面,它運行時錯誤的參數數量錯誤或屬性賦值無效 – Jez

+1

您的更新SQL不返回任何記錄,所以您希望記錄集爲空。對於更新,使用'Connection.Execute'方法會更好 - 您可以使用一個參數'RecordsAffected'來確定更新會影響多少行。 http://msdn.microsoft.com/en-us/library/windows/desktop/ms675023(v=vs.85).aspx –

回答

2

以下是我曾經能夠更新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