Sub Test()
Dim fn$, s$, ws As Worksheet, a(1 To 7)
'Inputs
fn = CreateObject("WScript.Shell").specialfolders("Desktop") & "\ken.xlsx"
s = "Worksheet5"
'Exit if fn does not exist.
If Dir(fn) = "" Then
MsgBox fn, vbCritical, "Macro Ending - File Does Not Exist:"
Exit Sub
End If
'Exit if worksheet "s" does not exist.
If WorkSheetExists() Then
Set ws = Sheets("Worksheet5")
Else
MsgBox "WorkSheet: " & s, vbCritical, "Macro Ending - WorkSheet Does Not Exist:"
Exit Sub
End If
a(1) = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Password="""";" & _
"User ID=Admin;Data Source=" & fn & ";Mode=Share Deny "
a(2) = "Write;Extended Properties=""HDR=YES;"";Jet OLEDB:System database="""";" & _
"Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet "
a(3) = "OLEDB:Engine Type=37;Jet OLEDB:Database Locking Mode=0;" & _
"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;"
a(4) = "Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;" & _
"Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy "
a(5) = "Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;" & _
"Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;"
a(6) = "Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;" & _
"Jet OLEDB:Bypass ChoiceField Validation=False"
a(7) = "Destination:=" & ws.Range("A1")
With ws.ListObjects.Add(SourceType:=xlSrcExternal, Source:=a).QueryTable
.CommandType = xlCmdTable
.CommandText = Array("'Inbound Flight$'")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceDataFile = fn
.Refresh BackgroundQuery:=False
End With
End Sub
'WorkSheetExists in a workbook:
Function WorkSheetExists(sWorkSheet As String, Optional sWorkbook As String = "") As Boolean
Dim ws As Worksheet, wb As Workbook
On Error GoTo notExists
If sWorkbook = "" Then
Set wb = ActiveWorkbook
Else
Set wb = Workbooks(sWorkbook) 'sWorkbook must be open already. e.g. ken.xlsm, not x:\ken.xlsm.
End If
Set ws = wb.Worksheets(sWorkSheet)
WorkSheetExists = True
Exit Function
notExists:
WorkSheetExists = False
End Function