使用Excel VBA运行SQL查询

我对SQL和VBA相当陌生。 我已经写了一个SQL查询,我希望能够调用并从Excel工作簿中的VBA子运行,然后将查询结果放入工作簿。 我发现了一些在线(stackoverflow和其他地方)声称这样做,但我无法理解他们,因为他们不包含任何解释。 例如,这里是我在网上find的一个子文件:

Sub ConnectSqlServer() Dim conn As ADODB.Connection Dim rs As ADODB.Recordset Dim sConnString As String ' Create the connection string. sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _ "Initial Catalog=MyDatabaseName;" & _ "Integrated Security=SSPI;" ' Create the Connection and Recordset objects. Set conn = New ADODB.Connection Set rs = New ADODB.Recordset ' Open the connection and execute. conn.Open sConnString Set rs = conn.Execute("SELECT * FROM Table1;") ' Check we have data. If Not rs.EOF Then ' Transfer result. Sheets(1).Range("A1").CopyFromRecordset rs ' Close the recordset rs.Close Else MsgBox "Error: No records returned.", vbCritical End If ' Clean up If CBool(conn.State And adStateOpen) Then conn.Close Set conn = Nothing Set rs = Nothing End Sub 

首先,这会工作吗? 其次,我需要在子文件(它看起来像提供商,数据源,初始目录等)中取代我在哪里可以find信息来replace它们?

我希望这个问题不是太混乱,我感谢你的帮助!

以下是我目前用于将数据从MS SQL Server 2008中提取到VBA中的代码。 您需要确保您有适当的ADODB参考[ VBA编辑器 – >工具 – >参考 ],并确保您有Microsoft ActiveX数据对象2.8库检查,这是检查底部行的第二(我正在使用Windows 7上的Excel 2010;您可能会有一个稍微不同的ActiveX版本,但仍然以Microsoft ActiveX开头):

SQL所需的参考

使用远程主机和用户名/密码连接到MS SQL的子模块

 Sub Download_Standard_BOM() 'Initializes variables Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim ConnectionString As String Dim StrQuery As String 'Setup the connection string for accessing MS SQL database 'Make sure to change: '1: PASSWORD '2: USERNAME '3: REMOTE_IP_ADDRESS '4: DATABASE ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE" 'Opens connection to the database cnn.Open ConnectionString 'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value cnn.CommandTimeout = 900 'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid StrQuery = "SELECT TOP 10 * FROM tbl_table" 'Performs the actual query rst.Open StrQuery, cnn 'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook Sheets(1).Range("A2").CopyFromRecordset rst End Sub