I have 2 Select statements that I need to have both in 1 statement to avoid the manual lookup I do every time updating the Data sheet to determine which account is above 250 K and which is below 250K. Please take a look at these 2 statements:
Once this routine is completed, I look up the Temp sheet and update the data sheet with the above 250 or below 250 categories. If there’s a way to merge the second statement into the first one(vsql), that’d be much appreciated.
Thank you
Option Explicit
Public Sub Update_Data()
Dim vFile As Variant: vFile = Application.GetOpenFilename(FileFilter:="All Files (*.*), *.*", Title:="Select The Strat Report", MultiSelect:=False)
If vFile = False Then End
On Error GoTo errorhandler
Dim Conn, Rs As Object, vSql As String, vDt As String
Set Conn = CreateObject("ADODB.Connection")
With Conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & vFile & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=Yes;IMEX=1"";"
.Open
End With
'the calculated field AGG is the key to determine which account is >250K and which is below 250
vSql = "SELECT T1.* " & _
",IIF(T1.[Due Date] <= #" & 30 / 5 / 2024 & "# AND T1.[Inv Type] = 'INV', T1.[Outstanding]) AS [AGG] " & _
"FROM [Transactions$B11:CK150000] T1 " & _
"ORDER BY T1.[Outstanding] DESC"
Set Rs = Conn.Execute(vSql)
Sheets("Data").Cells(2, 1).CopyFromRecordset Rs 'everything at invoices level(multiple rows each account)
Set Rs = Conn.Execute("SELECT T1.[Customer Number],T1.[Customer Name] " & _
"FROM ([Excel 12.0 Xml;HDR=Yes;Database=" & ThisWorkbook.FullName & "].[Data$] T1 " & _
"INNER JOIN " & _
"(SELECT [Customer Number],sum([AGG]) FROM [Excel 12.0 Xml;HDR=Yes;Database=" & ThisWorkbook.FullName & "].[Data$] " & _
"GROUP BY [Customer Number] HAVING sum([AGG])>=" & 250000 & ") as T2 " & _
"ON T1.[Customer Number] = T2.[Customer Number]) " & _
"WHERE T1.[Inv Type] = 'INV' AND T1.[Due Date] <= #" & 30 / 5 / 2024 & "# " & _
"GROUP BY T1.[Customer Number],T1.[Customer Name]")
Sheets("Temp").Cells(2, 1).CopyFromRecordset Rs 'customer account level(1 row each account)
Rs.Close
Conn.Close
Set Conn = Nothing
Set Rs = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
Exit Sub
errorhandler:
If Not (Rs Is Nothing) Then
If (Rs.State And 1) = 1 Then Rs.Close
Set Rs = Nothing
End If
MsgBox "Error " & Err.Number & " (" & Err.Description & ") " & Err.Source
End Sub