2010-04-02 144 views
1

我有一個小型的Excel程序。Excel VBA SQL數據

我想能夠使用此程序來更新SQL表。

會是什麼功能說在數據庫SQL表測試ABC

感謝

回答

0

我看你還有其他疑問打開處理實際連接到SQL Server,所以我贏了更新線2再加上討論。

關係數據庫表並不認爲事物是按照某個順序排列的,所以你不能真正說某個記錄是「記錄2」或「行2」,只是因爲你把它添加到了表中。除非你使用一個字段來創建一個ID號碼,這個ID號碼會隨着每個新記錄的增加而增加。

然後你就可以說

UPDATE Test SET YourField=NewValue WHERE IDfield=2

Here's more information on the UPDATE command,如果你需要訪問該記錄。

3

首先,您需要添加對ActiveX數據對象庫的引用,其中包含允許您執行數據庫訪問的對象集 - 在Excel Visual Basic編輯器中,轉到工具|引用...在對話框中,向下滾動,直到找到Microsoft ActiveX Data Objects 2.8 Library。選中庫名旁邊的複選框。
VBA References dialog with ADO library checked http://philippursglove.com/stackoverflow/adoreference.png

你的代碼來更新數據庫,然後應該是這個樣子(使用SQL從JohnK813的答案):

'Declare some variables 
Dim cnn As ADODB.Connection 
Dim cmd As ADODB.Command 
Dim strSQL As String 

'Create a new Connection object 
Set cnn = New ADODB.Connection 

'Set the connection string 
cnn.ConnectionString = myDatabaseConnectionString 'See http://connectionstrings.com if you need help on building this string for your database! 

'Create a new Command object 
Set cmd = New ADODB.Command 

'Associate the command with the connection 
cmd.ActiveConnection = cnn 

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure 
cmd.CommandType = adCmdText 

'Create the SQL 
strSQL = "UPDATE Test SET YourField = NeValue WHERE IDField = 2" 

'Pass the SQL to the Command object 
cmd.CommandText = strSQL 

'Open the Connection to the database 
cnn.Open 

'Execute the bit of SQL to update the database 
cmd.Execute 

'Close the connection again 
cnn.Close 

'Remove the objects 
Set cmd = Nothing 
Set cnn = Nothing 
+0

謝謝!該片段很有幫助。 – 2012-02-29 10:57:07