Using Excel VBA to run SQL query Using Excel VBA to run SQL query vba vba

Using Excel VBA to run SQL query


Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()'Initializes variablesDim cnn As New ADODB.ConnectionDim rst As New ADODB.RecordsetDim ConnectionString As StringDim 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 rstEnd Sub