Sub GetMainSummary()
Dim WSOrig As Worksheet
Dim WSTemp As Worksheet
Dim FinalRow As Long
Dim sType As String
Dim sBU As String
Dim sRegion As String
Dim shDest As Worksheet
Dim sDataSource As String
Dim MyConn
Dim dtFirst As Double
Dim dtLast As Double
Dim i As Integer
Dim LastRow As Long, lOffset As Long
Dim fld As Field
Dim Rws As Long
fPATH = "the full path to the .mdb file"
sFileID = ActiveWorkbook.FullName
dtFirst = CDbl(Range("FirstDate").Value)
dtLast = CDbl(Range("LastDate").Value)
shDest = "Main"
sDataSource = "qryDataToImport" 'import data by month
Set WSOrig = Sheets("Setup")
sBU = Range("State").Value
sVersion = Range("Version").Value
sSQL = "SELECT * FROM " & sDataSource
'original Business Unit filter
If sBU = "" Then
sSQL = sSQL
Else
If InStr(1, sSQL, "WHERE") > 1 Then
sSQL = sSQL & " AND BusinessUnit=" & "'" & sBU & "'"
Else
sSQL = sSQL & " WHERE BusinessUnit=" & "'" & sBU & "'"
End If
End If
'filter by date: uses two defined ranges in the workbook
If i = 1 Then 'main data
If InStr(1, sSQL, "WHERE") > 1 Then
sSQL = sSQL & " AND Fcst_Date BETWEEN " & dtFirst & " AND " & dtLast
Else
sSQL = sSQL & " WHERE Fcst_Date BETWEEN " & dtFirst & " AND " & dtLast
End If
End If
Debug.Print sSQL
MyConn = fPATH
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:=sSQL, ActiveConnection:=cnn, _
CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, _
Options:=adCmdText
Application.ScreenUpdating = False
Set WSTemp = Worksheets(varSources(i, 1))
WSTemp.Activate
Range("A1").CurrentRegion.Offset(1, 0).Clear
With Range("A1") 'create field headers
lOffset = 0
For Each fld In rst.Fields
.Offset(0, lOffset).Value = fld.Name
lOffset = lOffset + 1
Next fld
End With
Range("A2").CopyFromRecordset rst
rst.Close
Sheets("Setup").Activate
Application.ScreenUpdating = True
End Sub