SQL Connection
Windows Authentication - Connection String
Ex: Data Source=PavanSys-PC\PAVAN;"
In this case ForExcel is the database name
Dim str As String
str = "Provider=SQLOLEDB;Data Source=PavanSys-PC\PAVAN;" & _
"Initial Catalog=ForExcel;Integrated Security=SSPI"
SQL Server Authentication - Connection String
Dim str As String
str = "Provider=SQLOLEDB;" & _
"Data Source=SRIRAM-PC\PAVAN;" & _
"Initial Catalog=Forexcel;" & _
"User ID=xxxx;Password=xxxxx;"
Once we connected to database We can retrieve data based on two methods
SQL Server OLE DB CONNECTION
Sub RetrieveData_From_SQLDatabase_To_Excel()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim str As String
str = "Provider=SQLOLEDB;Data Source=SRIRAM-PC\PAVAN;" & _
"Initial Catalog=ForExcel;Integrated Security=SSPI"
cn.Open str
rs.Open _
Source:="Select P.Period, P.Item, P.Purchase_Qty, P.Purchase_Price, S.Sales_Qty, S.Sales_Price from Purchases_Q1 as P Right outer join Sales_Q1 as S on P.Item = S.Item", _
ActiveConnection:=cn, _
CursorType:=adOpenDynamic, _
LockType:=adLockReadOnly, _
Options:=adCmdText
Dim Wkb As Workbook
Set Wkb = Workbooks.Add
With ActiveSheet.QueryTables _
.Add(Connection:=rs, _
Destination:=Wkb.Sheets("sheet1").Range("D5"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.RefreshPeriod = 0
.AdjustColumnWidth = True
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
.EnableEditing = True
.SavePassword = True
.SaveData = True
End With
Call Formatting_Output
End Sub
Designing Template - SQL to Excel Connection
Joining all the columns from multiple tabels