The AnalystCave.com addin mentioned is essentially a wizard to create Querytables, which are a standard excel feature. Once created the QueryTable is saved with the workbook and the addin is no longer needed.
Excel also provides the user a way to create these QueryTables (without using VBA) but the process is horrible.
Having just used the addin, I would recommend using it, and recommend not writing your own VBA code to create the QueryTable for yourself (as it's time consuming). However if you do want to create them using VBA here is some code to start you off.
Note that an alternative is to use MS PowerQuery, but for simple stuff the addin is much easier and quicker than power query (well done Microsoft, but the addin author wins this round)
Sub CreateAQueryConnection()
Dim wks As Worksheet
Dim MyConnection As String
Dim qt As QueryTable
Set wks = ActiveSheet
'Clear worksheet of old QueryTables
For Each qt In wks.QueryTables
qt.Delete
Next qt
' Build a connection string using http://www.connectionstrings.com/excel/
' (The one below is overkill!)
MyConnection = Join(Array( _
"OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\Users\Harvey\OneDrive\My Study\Excel Study\SQL Addin1.xlsx;Mode=S" _
, "hare Deny Write;Extended Properties=""Excel 12.0 Xml;HDR=YES"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:E" _
, "ngine Type=35;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLE" _
, "DB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale " _
, "on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLE" _
, "DB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False" _
), "")
'Check if querytable exists
If wks.QueryTables.Count > 0 Then
Set qt = wks.QueryTables("qt" & wks.codename)
Else
Set qt = wks.QueryTables.Add(Connection:=MyConnection, Destination:=wks.Cells(1, 1))
End If
With qt
.CommandType = xlCmdSql
' Yuo will need to chnage the sql that you use
.CommandText = Array("SELECT T1.* FROM [Sheet1$] AS T1")
' you could set the name here - it's done already
' .Name = ""
.FieldNames = True
.RowNumbers = False
.AdjustColumnWidth = True
.FillAdjacentFormulas = True
.PreserveFormatting = True
.PreserveColumnInfo = False
.SavePassword = False
.SaveData = True
.RefreshOnFileOpen = True
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.RefreshPeriod = 60
.Refresh BackgroundQuery:=False
End With
' Set ExecuteSQL = qt.ResultRange
Debug.Print qt.ResultRange.Address
End Sub