Forgive my ignorance right off the bat, I am a fabricobbler. I am trying to modify an existing query. My thought process is that I can let this strsql query run, populate the results to excel, then query a specific range in the query for the date range, run a for each loop on the range to query a sql database, compare the date ranges and pull in a shift name. I can get the macro all the way to the point of looking at the specified range, debug that range to the immediate window, but I can't get it to populate the querytable to the specified range. It acts like it doesn't even try to look at the sql table I am telling it to look at. I will attempt to paste the code below. Also, this code is written after the fact, and placed in the original macro as a call method. I am wide open to any and all suggestions as to how to make this better. I have perused the forum and google for far too long, I am sure this question has been posed before and I apologize. There are also snippets of different methods I have tried interlaced all throughout the code, and for that I apologize.
Sub GetShift()
Dim strsql As String
Dim rg1 As Range
Dim i As Long
Dim j As Variant
Dim coll As New Collection
Dim ary As Variant
Sheets("Data").Select
'rg1 = Range("C2:C10000")
Range("C2", Range("C" & Rows.Count).End(xlUp)).Select
ary = Selection
'Set rg = Sheets("Data").Range("C2", Range("C" & Rows.Count).End(xlUp)).Select
'coll.Add rg1
ary = selection
For Each j In ary
Debug.Print j
strsql = "SELECT Hist_Shift_Code"
strsql = strsql & " From ""1802_SHIFT"""
strsql = strsql & " where ""Hist_Shift_Start"" >= '" & ary & "' " 'I have tried umpteen different names here for the date ranges. this was a last attempt, handful of noodles at the wall
strsql = strsql & " and ""Hist_Shift_Start"" < '" & ary & "'"
server = "ODBC;DSN=*****" 'I commented out the actual server name for security reasons
Next
On Error GoTo ErrorHandler
With ActiveSheet.QueryTables.Add(server, _
Destination:=Range("A1"))
.Sql = (strsql)
.FieldNames = True
.RefreshStyle = xlInsertDeleteCells
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.HasAutoFormat = True
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SavePassword = True
.SaveData = True
End With
' End If
' Next I
ErrorHandler: ' Error-handling routine.
End Sub