Sub GetData(SrcFile As Variant, SrcSheet As String, SrcRange As String, Target As Range, Header As Boolean, UseHeaderRow As Boolean)
Dim rsCon As Object, rsData As Object
Dim szConnect As String, szSQL As String
Dim lCount As Long
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SrcFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=" & IIf(Header, "Yes", "No") & """;"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & SrcFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=" & IIf(Header, "Yes", "No") & """;"
End If
If SrcSheet = "" Then
szSQL = "SELECT * FROM " & SrcRange$ & ";"
Else
szSQL = "SELECT * FROM [" & SrcSheet$ & "$" & SrcRange$ & "];"
End If
On Error GoTo ExitSub
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
If Not rsData.EOF Then
If Header = False Then
Target.Cells(1, 1).CopyFromRecordset rsData
Else
If UseHeaderRow Then
For lCount = 0 To rsData.Fields.Count - 1
Target.Cells(1, 1 + lCount).Value = rsData.Fields(lCount).Name
Next
Target.Cells(2, 1).CopyFromRecordset rsData
Else
Target.Cells(1, 1).CopyFromRecordset rsData
End If
End If
End If
rsData.Close: Set rsData = Nothing
rsCon.Close: Set rsCon = Nothing
Exit Sub
ExitSub:
End Sub