Last active
August 3, 2023 00:48
-
-
Save radum/4cd098e5379cbf2bc650 to your computer and use it in GitHub Desktop.
Query MS SQL Server With Excel VBA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Before we can start you’ll need to add a reference to your VBA project: | |
' Microsoft ActiveX Data Objects x.x Library | |
Option Explicit | |
Private Conn As ADODB.Connection | |
Function ConnectToDB(Server As String, Database As String) As Boolean | |
Set Conn = New ADODB.Connection | |
On Error Resume Next | |
Conn.ConnectionString = "Provider=SQLOLEDB.1; Integrated Security=SSPI; Server=" & Server & "; Database=" & Database & ";" | |
Conn.Open | |
If Conn.State = 0 Then | |
ConnectToDB = False | |
Else | |
ConnectToDB = True | |
End If | |
End Function | |
Function Query(SQL As String) | |
Dim recordSet As ADODB.recordSet | |
Dim Field As ADODB.Field | |
Dim Col As Long | |
Set recordSet = New ADODB.recordSet | |
recordSet.Open SQL, Conn, adOpenStatic, adLockReadOnly, adCmdText | |
If recordSet.State Then | |
Col = 1 | |
For Each Field In recordSet.Fields | |
Cells(1, Col) = Field.Name | |
Col = Col + 1 | |
Next Field | |
Cells(2, 1).CopyFromRecordset recordSet | |
Set recordSet = Nothing | |
End If | |
End Function | |
Public Sub Run() | |
Dim SQL As String | |
Dim Connected As Boolean | |
SQL = "SELECT * FROM QUOTA_Quota" | |
Connected = ConnectToDB("SQL_SERVER", "DB_Name") | |
If Connected Then | |
Call Query(SQL) | |
Conn.Close | |
Else | |
MsgBox "Huston we have a problem!" | |
End If | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Excel SQL AddIn makes it easy to create SQL queries in Excel:
http://www.analystcave.com/excel-tools/excel-sql-add-in-free/
Executing/editing the queries later does not require any addin obviously (OLEDB)