Querying SQL from VBA in Excel
Utilizing VBA within Excel, you can extend the functionality of your spreadsheets by directly interacting with SQL databases. This allows you to execute SQL queries, retrieve results, and integrate them into your Excel workbooks.
Consider the following VBA subroutine, which connects to a specific SQL Server instance and executes a SQL query:
Sub ConnectSqlServer() Dim conn As ADODB.Connection Dim rs As ADODB.Recordset Dim sConnString As String ' Adjust according to your environment sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _ "Initial Catalog=MyDatabaseName;" & _ "Integrated Security=SSPI;" ' Create connection and recordset objects Set conn = New ADODB.Connection Set rs = New ADODB.Recordset ' Open connection and execute query conn.Open sConnString Set rs = conn.Execute("SELECT * FROM Table1;") ' Check for data If Not rs.EOF Then ' Transfer results to Excel sheet Sheets(1).Range("A1").CopyFromRecordset rs ' Close 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
To use this subroutine, modify the following portions:
Once modified, run the VBA subroutine to establish a connection, execute the SQL query specified in the "Execute" statement, and populate the results onto the specified Excel sheet.
The above is the detailed content of How Can I Query a SQL Database Directly from My Excel VBA Code?. For more information, please follow other related articles on the PHP Chinese website!