Sub DinhMuc_HLMT()
Dim strSQL As String, strCon As String, i As Integer
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0 Xml;HDR=No"""
strSQL = "Select b.F1 as MaSP,b.F2 as TenSP,Sum(b.F4) as SoLuong,b.F3 as PhienBan,a.F5 as MaNVL1,a.F6 as MaNVL2,a.F7 as TenNVL1,a.F8 as TenNVL2,a.F9 as ChungLoai,a.F11 as LoaiSat,a.F12 as DoMa,Sum(a.F13*b.F4) as DinhMuc From [DINH MUC$B4:N] a Inner Join [Du Lieu$B4:E] b On a.F1=b.F1 and a.F3=b.F3 Group By b.F1,b.F2,b.F3,a.F5,a.F6,a.F7,a.F8,a.F9,a.F11,a.F12"
Sheet2.Range("A1:L1000").ClearContents
Sheet5.Range("A1:T1000").ClearContents
With CreateObject("ADODB.Recordset")
.Open (strSQL), strCon
Sheet2.Range("A2").CopyFromRecordset .DataSource
For i = 0 To .Fields.Count - 1
Sheet2.Cells(1, i + 1) = .Fields(i).Name
Next
.Close
.Open ("Transform Sum(DinhMuc)Select MaNVL1,MaNVL2,TenNVL1,TenNVL2,ChungLoai,LoaiSat,DoMa,sum(DinhMuc) as TongDM From (" & strSQL & ") Group By MaNVL1,MaNVL2,TenNVL1,TenNVL2,ChungLoai,LoaiSat,DoMa Pivot PhienBan"), strCon
Sheet5.Range("A2").CopyFromRecordset .DataSource
For i = 0 To .Fields.Count - 1
Sheet5.Cells(1, i + 1) = .Fields(i).Name
Next
End With
Sheet2.Activate
End Sub