Excel VBA SQL数据

我有一个小型的Excel程序。

我想能够使用这个程序来更新一个SQL表。

在数据库ABC的SQL表Test中更新第2行的函数是什么

谢谢

首先,您需要添加对ActiveX数据对象库的引用,其中包含允许您执行数据库访问的对象集 – 在Excel Visual Basic编辑器中,转到工具|引用…在对话框中,向下滚动,直到findMicrosoft ActiveX数据对象2.8库。 选中图书馆名称旁边的checkbox。
VBA参考对话框与ADO库检查http://philippursglove.com/stackoverflow/adoreference.png

你的代码更新数据库应该看起来像这样(使用JohnK813的答案SQL):

'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 

我看到你还有其他的问题需要处理,实际上连接到SQL Server,所以我不会在讨论中join更多的东西。

关系型数据库表并不认为事物是按照某种顺序排列的,所以你不能仅仅因为你把它添加到表中而把某个logging称为“logging2”或“行2”。 除非你使用一个字段来创build一个ID号码,每增加一个新的logging就会增加一个ID号码。

那么你可以通过说出来访问这个logging

UPDATE Test SET YourField=NewValue WHERE IDfield=2

如果你需要的话, 这里有关于UPDATE命令的更多信息 。