Function CreateQueryTable(sSQL As String, Optional bFieldNames As Boolean, Optional loc, Optional cn, Optional QueryOrSQL, Optional p1, Optional p2, Optional p3, Optional p4) As Boolean
' Create query table from external data source.
' Takes a valid ADO connection string and a
' valid SQL SELECT statement.
' bFieldNames = true and the fieldnames are included in results
' loc = location of where to put the results, default to A1
' cn = ADODB.Connection, defaults to Fusiondaily on Jupiter
Dim sMsg As String
'Dim cnnConnect As ADODB.Connection
Dim rstData As ADODB.Recordset
Dim qtbData As Excel.QueryTable
Dim wksNew As Excel.Worksheet
On Error GoTo CreateQueryTable_Err
If IsMissing(cn) Then
Set cn = gADO
End If
If IsMissing(loc) Then
Set loc = Range("A1")
End If
Set rstData = GetRecordset(sSQL, cn, QueryOrSQL, p1, p2, p3, p4)
If Err <> 0 Then
Err.Raise Err, "", Error
End If
' Add new worksheet.
Set wksNew = ActiveSheet
' Create query table in new worksheet.
Set qtbData = _
wksNew.QueryTables.Add(rstData, loc)
' Refresh query table to display data.
qtbData.FieldNames = bFieldNames
qtbData.Refresh
'qtbData.RefreshPeriod = 1
CreateQueryTable = True
CreateQueryTable_End:
On Error Resume Next
rstData.Close
Set rstData = Nothing
qtbData.Delete
Set qtbData = Nothing