Sub TongHop_HLMT()
Dim adoConn As Object, adoRS As Object
Set adoConn = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.Recordset")
With adoConn
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.FullName & _
";Extended Properties=""Excel 8.0;HDR=No;"";"
.Open
End With
With adoRS
.ActiveConnection = adoConn
.Open "SELECT F3, F4, Sum(TongNhap), Sum(TongXuat) " & _
"FROM (SELECT F1, F3, F4, Sum(F5) AS TongNhap, Sum(F6) AS TongXuat " & _
"FROM (SELECT F1, F3, F4, F5, null as F6 from [nhap$A2:E20000] " & _
"UNION ALL select F1, F5, F6,null, F7 FROM [Xuat$A2:G20000]) " & _
"GROUP BY F1, F3, F4 " & _
"HAVING F3 Is Not Null and F1 between #" & _
Format(DateSerial(Year(Sheet3.[d1]), Month(Sheet3.[d1]), Day(Sheet3.[d1])), "mm/dd/yyyy") & "# AND #" & _
Format(DateSerial(Year(Sheet3.[d2]), Month(Sheet3.[d2]), Day(Sheet3.[d2])), "mm/dd/yyyy") & "#) " & _
"GROUP BY F3, F4"
End With
With Sheet3
.Range("A5:E65000").ClearContents
.Range("B5").CopyFromRecordset adoRS
.Range("A5:A" & .Range("B65000").End(xlUp).Row) = "=ROW()-4"
End With
adoRS.Close: Set adoRS = Nothing
adoConn.Close: Set adoConn = Nothing
End Sub