Home » excel » Group Data using SQL "Group By" function in Excel VBA

Group Data using SQL "Group By" function in Excel VBA

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have two tables (1&2) that should be merged into a third (3) one.

Table1: F_Number, A_Number, A_Weight
Table2: A_Number, A_Country
Table3: F_Number, A_Country, A_Weight

The thrid table should be grouped by F_Number summing up A_Weight where A_Country has the same value. The joining of the tables works fine so far:

Dim strSQL As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String

DBPath = ThisWorkbook.FullName
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

Conn.Open sconnect
    strSQL = "Select [Table1$].[F_Number], [Table2$].[A_Country], [Table1$].[A_Weight] From [Table1$] Inner Join [Table2$] On [Table2$].[A_Number]=[Table1$].[A_Number]"
    mrs.Open strSQL, Conn
    ActiveSheet.Range("A2").CopyFromRecordset mrs
    mrs.Close
Conn.Close

The Result is a table like this:

F_Number; A_country; A_Weight
F_1; US; 10%
F_1: US; 10%
F_1; UK; 80%
F_2; UK; 100%

I want this table to be grouped by “A_Weight” like this:

F_Number; A_country; A_Weight
F_1; US; 20%
F_1; UK; 80%
F_2; UK; 100%

I do not know much about SQL, but what I tried so far is to sum up A_Weight and Group the result by F_Number, which gives me an error message. I am using a german office version, thus I can only try to translate the error: “Automatization Error”. I am still thinking it should work something like this.

Here is my non-working code for the SQL-String:

strSQL = "Select [Table1$].[F_Number], [Table2$].[A_Country], Sum([Table1$].[A_Weight]) From [Table1$] Inner Join [Table2$] On [Table2$].[A_Number]=[Table1$].[A_Number] Group By [Table1$].[F_Number]"
How to&Answers:

Your code is fine; you just need to modify the SQL query.

strSQL = "SELECT [Table1$].[F_Number], [Table2$].[A_Country], SUM([Table1$].[A_Weight]) " & _
         "FROM [Table1$], [Table2$] " & _
         "WHERE [Table2$].[A_Number] = [Table1$].[A_Number] " & _
         "GROUP BY [Table1$].[F_Number], [Table2$].[A_Country]"