I am receiving a general ODBC error when executing the code below. I also receive a pop-up box before the error to Enter Parameter Value for parameter1. I do not know what range is incorrectly referenced in my code.
Sub CIABIConnect()
Dim sConn As String
Dim sSql As String
Dim oQt As QueryTable
Dim part As String
Dim fromDate As String
Dim toDate As String
Dim reportSelect As String
Dim thisBook As Workbook
Dim inSheet As Worksheet
Dim outSheet As Worksheet
Dim connName As String
Dim todateString As String
Dim fromdateString As String
Dim locString As String
Dim lastRow As Integer
Set thisBook = ActiveWorkbook
Set inSheet = thisBook.Worksheets("Direct Query")
Set outSheet = thisBook.Worksheets("Direct Data")
inSheet.Select
inSheet.Range("B6").Activate
lastRow = inSheet.UsedRange.Rows.Count
fromDate = Format(inSheet.Cells(2, 2).Value, "yyyymmdd")
toDate = Format(inSheet.Cells(3, 2).Value, "yyyymmdd")
fromdateString = " '" & fromDate & "' "
todateString = " '" & toDate & "' "
connName = inSheet.Cells(11, 2).Value
Call deleteConnections
outSheet.Cells.Clear
outSheet.Select
sConn = "ODBC;DSN=" & connName
sConn = sConn & ";DBQ=" & connName
sConn = sConn & ";"
For i = 2 To lastRow
Select Case i
Case 37: sSql = sSql & inSheet.Cells(i, 4).Value & fromdateString
Case 38: sSql = sSql & inSheet.Cells(i, 4).Value & todateString
Case Else: sSql = sSql & inSheet.Cells(i, 4).Value
End Select
Next i
Set oQt = ActiveSheet.QueryTables.Add( _
Connection:=sConn, _
Destination:=outSheet.Range("a1"), _
Sql:=sSql)
oQt.refresh
CrwOut.Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Columns.AutoFit
End Sub
Sub deleteConnections()
For Each conn In ThisWorkbook.Connections
conn.Delete
Next conn
End Sub
SQL:
SELECT
'Direct from APIA' as source_nm
,itm.merch_cat_desc
,case
when data.purchase_type='EDGE' then 'Edge'
when data.purchase_type='TRADITIONAL' then 'Traditional'
else '?'
end "EDGE/NON-EDGE"
,sum(data.item_qty) as Net_Quantity
,sum(data.bams_price) as Net_Cost
,sum(data.revenue) as Net_Revenue
,sum(DATA.IT_DISC_AMT * SIGN (DATA.ITEM_QTY)) as Net_Discount
,sum( case
when data.item_qty > 0 then data.revenue
else 0
end
) as Gross_Revenue
,sum(
case
when data.item_qty > 0 then data.item_qty
else 0
end
) as Gross_Quantity
FROM DATA
--
JOIN INV.INV_STORE_EXTRACT STORE ON STORE.STORE_ID = DATA.STORE
--
JOIN INV.INV_CODA_CHANNEL CODA ON CODA.CODA_DEPT = STORE.CODA_DEPT
--
JOIN INV.ITEM_LIST_DRM ITM ON ITM.ITEM_CD = DATA.ITEM_CODE
--
LEFT OUTER JOIN INV.PROGRAM_DRM PRGRM
ON ITM.EQP_ITEM_PROGRAM_RPTKEY = PRGRM.PROGRAM_RPTKEY
--
WHERE
data.ord_comp_date between
**20170426
and
20170427**
--data.acct_prd='201708'
and data.trade_in_ind = 'N'
and CODA.CHANNEL_CATEGORY='DIRECT'
and PRGRM.program_cd in ('APO','CPO','IOT','NEW','USED','VIR')
and ITM.EQP_CLASS_DESC='Wireless Devices'
group by
itm.merch_cat_desc
,case
when data.purchase_type='EDGE' then 'Edge'
when data.purchase_type='TRADITIONAL' then 'Traditional'
else '?'
end
Related
I need to get values from Sheet1 Column A (number of rows changes every day - can be more than 7,000) and Sheet2 Column B (also dynamic - changes every day), put those values from the columns into an array in STRING type (can be two arrays as long as I can use them in the query) and use the array in vba query WHERE ... IN ('array') to be run in MS-SQL server.
I've tried different ways to get the values into an array but have failed as many solutions offered need to use Array AS Variant when I need String type (to work in the query). One method that kind of worked was getting the values (comma separated) into one cell in another sheet and using that cell.value in the query. But that method is only good for total rows of 3000 or less. I've tried adding more - like cell2.value, cell3.value, but I would get errors (ex)if there were no values available for cell3.value. Please help.
Sub GetData()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim fld As ADODB.Field
Dim mssql As String
Dim row As Integer
Dim Col As Integer
Dim WB As ThisWorkbook
'============THIS IS THE PART I NEED HELP WITH ======================
Dim strArray() As String 'TRYING TO GET VALUES FROM COLUMN AS ARRAY
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.count).End(xlUp).row
ReDim strArray(1 To TotalRows)
For i = 1 To TotalRows
strArray(i) = Cells(i, 1).Value & "','" 'TRYING TO INCLUDE COMMAS BETWEEN VALUES
Next
'===========================================================================
Set WB = ThisWorkbook
Application.ScreenUpdating = False
Set oConn = New ADODB.Connection 'NEED TO CONNECT TO SQL SERVER TO RUN QUERY
Set rs = New ADODB.Recordset
mssql = "SELECT Order.ID, Order.OrderDate, Order.Account" _
& " FROM dbo.tbl_Order" _
& " WHERE Order.ID IN ('" & strArray() & "0'")" '<=== THIS IS WHERE I NEED TO INSERT STRING ARRAY
oConn.ConnectionString = "driver={SQL Server};" & _
"server=SERVER01;authenticateduser = TRUE;database=DATABASE01"
oConn.ConnectionTimeout = 30
oConn.Open
rs.Open mssql, oConn
If rs.EOF Then
MsgBox "No matching records found."
rs.Close
oConn.Close
Exit Sub
End If
' ===clear data in columns in worksheet as new values are copied over old ones
' ===this part is working fine
Worksheets("Sheet3").Range("A:P").ClearContents
' START WRITING DATA TO SHEET3
row = 5
Col = 1
For Each fld In rs.Fields
Sheet3.Cells(row, Col).Value = fld.Name
Col = Col + 1
Next
rs.MoveFirst
row = row + 1
Do While Not rs.EOF
Col = 1
For Each fld In rs.Fields
Sheet1.Cells(row, Col).Value = fld
Col = Col + 1
Next
row = row + 1
rs.MoveNext
Loop
rs.Close
oConn.Close
End Sub
You don't want to build an array but rather a string with the values you need. I stripped down your code to illustrate how this works:
Sub GetData()
Dim values As String
Dim mssql As String
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.Count).End(xlUp).row
For i = 1 To TotalRows
values = values & "'" & Cells(i, 1).Value & "',"
Next
values = Mid(values, 1, Len(values) - 1)
mssql = "SELECT Order.ID, Order.OrderDate, Order.Account " & _
"FROM dbo.tbl_Order " & _
"WHERE Order.ID IN (" & values & ")"
MsgBox mssql
End Sub
Get Zero-Based From Column
If you can use an array of strings (don't know SQL), for column A you could e.g. use:
Dim strArray() As String: strArray = getZeroBasedFromColumn(Range("A2"))
If you have to use a string then you will have to do:
Dim strArray As String
strArray = "'" & Join(getZeroBasedFromColumn(Range("A2")), "','") & "'"
and use strArray without the parentheses.
Qualify the first cell range (A2) appropriately e.g. WB.Worksheets("Sheet1").Range("A2").
Both solutions use the following function.
The Code
Function getZeroBasedFromColumn( _
FirstCell As Range) _
As Variant
Const ProcName As String = "getZeroBasedFromColumn"
On Error GoTo clearError
If Not FirstCell Is Nothing Then
Dim rg As Range
Set rg = FirstCell.Resize(FirstCell.Worksheet.Rows.Count - FirstCell.Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not rg Is Nothing Then
Set rg = FirstCell.Resize(rg.Row - FirstCell.Row + 1)
Dim rCount As Long: rCount = rg.Rows.Count
Dim Data As Variant
If rCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
Else
Data = rg.Value
End If
Dim arr() As String: ReDim arr(0 To rCount - 1)
Dim i As Long
For i = 1 To rCount
arr(i - 1) = CStr(Data(i, 1))
Next i
getZeroBasedFromColumn = arr
End If
End If
ProcExit:
Exit Function
clearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function
Sub getZeroBasedFromColumnTEST()
Dim arr() As String: arr = getZeroBasedFromColumn(Range("A1"))
End Sub
An alternative (if you have the necessary database permissions) is to create a temporary table and use a JOIN in place of the WHERE IN().
Option Explicit
Sub GetData()
' get list of order numbers from Col A Sheet1 and COl B Sheet2
Dim wb As Workbook, wsOut As Worksheet
Dim rngA As Range, rngB As Range
Dim ar, ar1, ar2, iLastRow As Long, SQL As String
Dim i As Long, n As Long, id As String
Set wb = ThisWorkbook
Set wsOut = wb.Sheets("Sheet3")
' copy sheet1 Column A into array ar1
iLastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).row
Set rngA = Sheet1.Range("A1:A" & iLastRow)
If rngA.Rows.Count = 1 Then
ar1 = Array(0, rngA.Cells(1, 1).Value2)
Else
ar1 = Application.Transpose(rngA.Value2)
End If
'Debug.Print "A", LBound(ar1), UBound(ar1)
' copy sheet2 column B into array ar2
iLastRow = Sheet2.Cells(Rows.Count, "B").End(xlUp).row
Set rngB = Sheet2.Range("B1:B" & iLastRow)
If rngB.Rows.Count = 1 Then
ar2 = Array(0, rngB.Cells(1, 1).Value2)
Else
ar2 = Application.Transpose(rngB.Value2)
End If
'Debug.Print "B", LBound(ar2), UBound(ar2)
' connect to DB and create temporary table
Dim oConn As New ADODB.Connection
With oConn
.ConnectionString = "driver={SQL Server};" & _
"server=SERVER01;authenticateduser = TRUE;database=DATABASE01"
.ConnectionTimeout = 30
.Open
End With
oConn.Execute "CREATE TABLE #tmp (ID varchar(20) NOT NULL,PRIMARY KEY (ID ASC))"
' prepare insert query
SQL = "INSERT INTO #tmp (ID) VALUES (?)"
Dim cmd As New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = oConn
.CommandText = SQL
.Parameters.Append .CreateParameter("p1", adVarChar, adParamInput, 20)
End With
' insert array values into temp table
Dim t0 As Single: t0 = Timer
For Each ar In Array(ar1, ar2)
oConn.BeginTrans
For i = 1 To UBound(ar)
id = Trim(ar(i))
If Len(id) > 0 Then
cmd.Execute n, id
End If
Next
oConn.CommitTrans
'Debug.Print i - 1 & " Inserted"
Next
n = oConn.Execute("SELECT COUNT(*) FROM #tmp")(0)
'Debug.Print n & " records inserted into #tmp in " & Format(Timer - t0, "#.0 secs")
' select records using join as where filter
SQL = " SELECT Ord.ID, Ord.OrderDate, Ord.Account" _
& " FROM [tbl_Order] as Ord" _
& " JOIN #tmp ON Ord.ID = #tmp.ID"
' output result
Dim rs As New ADODB.Recordset
Set rs = oConn.Execute(SQL, n)
wsOut.Range("A:P").ClearContents
' header
Dim fld, cell As Range
Set cell = wsOut.Cells(5, 1)
For Each fld In rs.Fields
cell = fld.Name
Set cell = cell.Offset(0, 1)
Next
' data
wsOut.Cells(6, 1).CopyFromRecordset rs
oConn.Close
' end
n = wsOut.Cells(Rows.Count, 1).End(xlUp).row - 6
MsgBox n & " rows witten in " & Format(Timer - t0, "0.00 secs")
End Sub
I have two workbooks one "database" and another "source". What I'm trying to achieve is to set up a loop that would iterate thru a known range in "source" wb and create links in "database". Data in the "source" wb = C7:C38.
Any ideas?
Code below is the one i'm using to pull single values for the links - how can I make it loop thru range C7:C38?
Option Explicit
'**********Using ip address to link/locate folders in the the directory.
Public Sub PullData()
Dim repDate As Date
Dim tmpFileStr As String
Dim tmpPathStr As String
Dim rowCtrLng As Long
Dim startRowCtrLng As Long
Dim stoptRowCtrLng As Long
Dim msgStr As String
Dim currentDate As Date
Dim stopDate
Dim fldName As String
Dim fName As String
Dim fDay As String
'On Error GoTo errHandler
'Initialize row counter
startRowCtrLng = 2
'Get starting row for new data
Do While ThisWorkbook.ActiveSheet.Range("B" & startRowCtrLng).Value <> ""
startRowCtrLng = startRowCtrLng + 1
Loop
rowCtrLng = startRowCtrLng
'Assign current date to variable
'Pause automatic calculation
Application.Calculation = xlCalculationManual
'Disable alerts
Application.DisplayAlerts = False
repDate = Format(ThisWorkbook.Worksheets("Database").Range("A" & rowCtrLng).Value, "mm/dd/yyyy")
currentDate = Date
fldName = Format(Year(Now), "0000")
fName = Format(Month(Now), "00")
fDay = Format(Day(Now), "0")
'Begin looping through date range
Do While repDate < currentDate
tmpFileStr = ""
tmpPathStr = ""
'Determine if report exists
tmpPathStr = "\\0.0.0.0\dept\Folder\Subfolder\" & fldName & "\"
If Dir("\\0.0.0.0\dept\Folder\Subfolder\" & fldName & "\" & fName & "-" & fldName & ".xls") <> "" Then
tmpFileStr = fName & "-" & fldName & ".xls"
Else
tmpFileStr = ""
End If
If tmpFileStr <> "" Then
'build Links
'Production Date
ThisWorkbook.ActiveSheet.Range("A" & rowCtrLng).Value = repDate
'Crush
ThisWorkbook.ActiveSheet.Range("B" & rowCtrLng).Value = "='" & tmpPathStr & "[" & tmpFileStr & "]C vol'!$C$7"
End If
rowCtrLng = rowCtrLng + 1
repDate = ThisWorkbook.Worksheets("Database").Range("A" & rowCtrLng).Value
Loop
End Sub
'
I've some code in Excel that updates an Access table based on if RTP_ID equals IngID, the following matches and works if they are numeric in RTP_ID:
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID = " & lngID
However I would like it where RTP_ID could be a string.
I've tried:
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID = '" & lngID & "'"
but that still doesn't work, any ideas?
So if RTP_ID was 1 it would work, but if it was 1A it wouldn't.
Edit- here is the code I currently have:
Application.ScreenUpdating = False
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
Dim MyConn
Dim lngRow As Long
Dim lngID, LR, Upd
Dim strID As String
Dim j As Long
Dim sSQL As String
LR = Range("B" & Rows.Count).End(xlUp).Row
Upd = LR - 1
lngRow = 2
Do While lngRow <= LR
strID = Cells(lngRow, 2).Value
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID2 = " & strID
Set cnn = New ADODB.Connection
MyConn = "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source =\Work\Sites\HLAA\NEW\test\HLAA 2015 NEW.mdb"
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open sSQL, ActiveConnection:=cnn, _
CursorType:=adOpenKeyset, LockType:=adLockOptimistic
.
With rst
.Fields("MonitorCapacity") = Cells(lngRow, 74).Value
rst.Update
End With
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
lngRow = lngRow + 1
Loop
MsgBox "You just updated " & Upd & " records"
I'd rewrite the code as below:
Dim cnn As Object
Dim lngRow As Long
Dim lngID As Long, LR As Long, Upd As Long
Dim strID As String
LR = ThisWorkbook.Worksheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
Upd = LR - 1
lngRow = 2
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=\Work\Sites\HLAA\NEW\test\HLAA 2015 NEW.mdb;" & _
"Persist Security Info=False;"
Do While lngRow <= LR
strID = ThisWorkbook.Worksheets("Sheet2").Cells(lngRow, 2).Value
cnn.Execute "UPDATE Tbl_Primary SET MonitorCapacity = '" & _
ThisWorkbook.Worksheets("Sheet2").Cells(lngRow, 74).Value2 & _
"' WHERE RTP_ID2 = '" & strID & "'"
lngRow = lngRow + 1
Loop
MsgBox "You just updated " & Upd & " records"
You may need to change the Worksheet name - when you just put Range("B" & Rows.Count) it will use whichever sheet is active at the time, so need to state the worksheet.
Im using a .accdb file and connecting with the following code, which has worked for me multiple times, so I don't know why its corrupting the file this time.
dbPath = ActiveWorkbook.Path & "\WaitAnalysisDB.accdb"
tblName = "Wait_Data_Table"
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & dbPath & "';"
conn.Open strcon
Does the "Unrecognized Format" Access error only occur due to an error in the connection string, or could it be my SQL statement inserting records as well? Thanks
Here's my code, if anyone cares to look through it. In the for loops that build the SQL statemetn (rcdDetail variable), I have an if statement, which basically says if there is a blank in Column A, then use the row above it that isnt blank.
Dim conn As New ADODB.Connection, rs As New ADODB.Recordset, dbPath As String, tblName As String
Dim rngColHeads As Range, rngTblRcds As Range, colHead As String, rcdDetail As String
Dim ch As Integer, cl As Integer, notNull As Boolean, strcon As String, lr As Integer
Dim currentdate As String
Dim strdbcheck As String
'Code Checks if There Are Records for the Date in the DB
'If there is, then it skips the SQL code
currentdate = Date
dbPath = ActiveWorkbook.Path & "\WaitAnalysisDB.accdb"
tblName = "Wait_Data_Table"
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & dbPath & "';"
conn.Open strcon
strdbcheck = "SELECT * FROM " & tblName
rs.Open strdbcheck, conn
rs.Filter = "Date= #" & currentdate & "#"
If Not rs.EOF Then
Set rs = Nothing
Set conn = Nothing
GoTo SkipExport
Else
Set rs = Nothing
Set conn = Nothing
GoTo Export
End If
Export:
'Set Up Connections
dbPath = ActiveWorkbook.Path & "\WaitAnalysisDB.accdb"
tblName = "Wait_Data_Table"
'Create Date Column
Worksheets("Wait Analysis DATA").Select
lr = Cells(Rows.Count, "K").End(xlUp).Row
currentdate = Date: Range("O1").Value = "Date": Range(Range("O2"), Range("O" & lr)).Value = currentdate
Set rngColHeads = ActiveSheet.Range(Range("a1"), Range("a1").End(xlToRight))
Set rngTblRcds = ActiveSheet.Range(Range("K2:k" & lr).Offset(0, -10), Range("K2:k" & lr).Offset(0, 4))
'SQL connection String
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & dbPath & "';"
'Create String for Columns for SQL
colHead = "(["
For ch = 1 To rngColHeads.Count
colHead = colHead & rngColHeads.Columns(ch).Value
Select Case ch
Case Is = rngColHeads.Count
colHead = colHead & "])"
Case Else
colHead = colHead & "],["
End Select
Next ch
On Error GoTo EndUpdate
conn.Open strcon
conn.BeginTrans
Dim tempcl As Integer
For cl = 1 To rngTblRcds.Rows.Count
If Range("a2").Offset(cl - 1, 0) = "" Then
tempcl = cl - Range("a2").Offset(cl, 0).End(xlUp).Rows.Count
notNull = False
rcdDetail = "('"
For ch = 1 To rngColHeads.Count
Select Case rngTblRcds.Rows(tempcl).Columns(ch).Value
Case Is = Empty
Select Case ch
Case Is = rngColHeads.Count
rcdDetail = Left(rcdDetail, Len(rcdDetail) - 1) & "NULL)"
Case Else
rcdDetail = Left(rcdDetail, Len(rcdDetail) - 1) & "NULL,'"
End Select
Case Else
notNull = True
Select Case ch
Case "11":
rcdDetail = rcdDetail & rngTblRcds.Rows(cl).Columns(ch).Value & "','"
Case Is = rngColHeads.Count
rcdDetail = rcdDetail & rngTblRcds.Rows(tempcl).Columns(ch).Value & "')"
Case Else
rcdDetail = rcdDetail & rngTblRcds.Rows(tempcl).Columns(ch).Value & "','"
End Select
End Select
Next ch
tempcl = 0
GoTo skipads
End If
notNull = False
rcdDetail = "('"
For ch = 1 To rngColHeads.Count
Select Case rngTblRcds.Rows(cl).Columns(ch).Value
Case Is = Empty
Select Case ch
Case Is = rngColHeads.Count
rcdDetail = Left(rcdDetail, Len(rcdDetail) - 1) & "NULL)"
Case Else
rcdDetail = Left(rcdDetail, Len(rcdDetail) - 1) & "NULL,'"
End Select
Case Else
notNull = True
Select Case ch
Case Is = rngColHeads.Count
rcdDetail = rcdDetail & rngTblRcds.Rows(cl).Columns(ch).Value & "')"
Case Else
rcdDetail = rcdDetail & rngTblRcds.Rows(cl).Columns(ch).Value & "','"
End Select
End Select
Next ch
skipads:
Select Case notNull
Case Is = True
rs.Open "INSERT INTO " & tblName & colHead & " VALUES " & rcdDetail, conn
Case Is = False
'do not insert record
End Select
Next cl
EndUpdate:
If Err.Number <> 0 Then
On Error Resume Next
conn.RollbackTrans
MsgBox "There was an error. This will exit the macro.", vbCritical, "Error!"
End
Else
On Error Resume Next
conn.CommitTrans
End If
conn.Close
Set rs = Nothing
Set conn = Nothing
On Error GoTo 0
SkipExport:
Everything looks ok, here's what I'd try.
Manually type the path for dbPath, moreover the entire connection string. Perhaps path isn't being populated correctly.
Here's the connection string you can follow:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;
If that doesn't work, double check your table name is correctly named. If it checks out, try wrapping your table name in []. So:
tblName = "[Wait_Data_Table]"
These are common things that give me grief, perhaps one of these are happening to you as well.
I'm trying to create a dropdown that upon changing the selection from the list of options will run a query that will insert the query results into the page. Here's what I have thus far:
Sub DropDown1_Change()
Dim dbConnect As String
Dim leagueCode As String
Dim leagueList As Range
Dim leagueVal As String
Dim TeamData As String
Set leagueList = Worksheets("Menu Choices").Range("A5:A10")
Set leagueVal = Worksheets("Menu Choices").Cell("B1").Value
leagueCode = Application.WorksheetFunction.Index(leagueList, leagueVal)
TeamData = "SELECT DISTINCT(Teams.teamID), name FROM Teams WHERE lgID = '" & leagueCode & "' & ORDER BY name ASC"
With Worksheets("Menu Choices").QueryTables.Add(Connection:=dbConnect, Destination:=Worksheets("Menu Choices").Range("D5"))
.CommandText = TeamData
.Name = "Team List Query"
.Refresh BackgroundQuery:=False
End With
End Sub
Anywho have any suggestions to get it working? Thanks in advance!
I was able to resolve the issue using similar code to the following:
Sub createTeamList()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQL As String
Dim inc As Integer
Dim topCell As Range
Dim leagueID As String
Dim leagueList As Range
Dim leagueChoice As Range
Set leagueList = Worksheets("Menu Choices").Range("A4:A9")
Set leagueChoice = Worksheets("Menu Choices").Range("B1")
leagueID = Application.WorksheetFunction.Index(leagueList, leagueChoice)
Set topCell = Worksheets("Menu Choices").Range("D4")
With topCell
Range(.Offset(1, 0), .Offset(0, 1).End(xlDown)).ClearContents
End With
With cn
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\lahman_57.mdb"
.Provider = "Microsoft Jet 4.0 OLE DB Provider"
.Open
End With
inc = 0
SQL = "SELECT teamID, name " _
& "FROM Teams " _
& "WHERE lgID = '" & leagueID & "' " _
& "GROUP BY teamID, name " _
& "ORDER BY name "
rs.Open SQL, cn
With rs
Do Until .EOF
topCell.Offset(inc, 0) = .Fields("teamID")
topCell.Offset(inc, 1) = .Fields("name")
inc = inc + 1
.MoveNext
Loop
End With
rs.Close
cn.Close
End Sub