kodr
Programmer
- Dec 4, 2003
- 368
I'm having trouble trying to perform a 'sum' query. My code is in Excel, and I'm trying to sum the totals of all records that have a certain region code, from an Access database.
I'm using MS ADO 2.8 as a reference, and here is my code so far..
I'm using MS ADO 2.8 as a reference, and here is my code so far..
Code:
Sub Global_Report(ByVal sOutFileName As String)
Dim iIndex As Integer
Dim iIndex2 As Integer
Dim dRegionTotals(10) As Double
Set Conn = New ADODB.Connection
Set RS = New ADODB.Recordset ' Query for RegionCodes
Set RS1 = New ADODB.Recordset ' Query for records within RegionCodes
With Conn
.Provider = "Microsoft.jet.oledb.4.0"
.ConnectionString = "data source = c:\OMTRU_Report\Config\OMTRU.mdb"
.CursorLocation = adUseClient
.Open
End With
iIndex2 = 1
sOutFileName = sOutFileName & "Global.xls"
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=sOutFileName _
, FileFormat:=xlNormal, Password:="", writerespassword:="" _
, ReadOnlyRecommended:=False, CreateBackup:=False
RS.Open "SELECT * FROM [State_Region]", Conn, adOpenStatic, adLockOptimistic
For iIndex = 1 To RS.RecordCount ' Problem below!!!
RS1.Open "SELECT SUM(TRU) as total FROM [Current_Recs] WHERE [State_Region]=" & RS.Fields(7).Value
dRegionTotals(iIndex2) = RS1("total")
iIndex2 = iIndex2 + 1
RS.MoveNext
RS1.Close
Next iIndex
RS.Close
Set RS = Nothing
Set RS1 = Nothing
Set Conn = Nothing
End Sub
[\code]
I know the following two lines don't work, but I'm at a loss here. Does anyone have any suggestions?
[code]
RS1.Open "SELECT SUM(TRU) as total FROM [Current_Recs] WHERE [State_Region]=" & RS.Fields(7).Value
dRegionTotals(iIndex2) = RS1("total")
[\code]
And finially, is there a better way to interface with Access type databases? I've found a lot of posts about using stored queries and was wondering if there's a better technique.
Thanks.