Các anh chị cho DHN46 hỏi: làm cách nào để đếm số lượng các mã số của 4 Sheet rồi hiển thị kết quả tại Sheet1, không đảo thứ tự sắp xếp các mã trên sheet1.
Xin cảm ơn GPE!
Gộp, đếm các mã đó đưa vào vùng tạm, dùng vùng tạm này cập nhật dữ liệu theo yêu cầu, cuối cùng xóa vùng tạm đi.
[GPECODE=sql]Sub GopSheet_HLMT()
Dim cn As Object, rst As Object, cat As Object, tbl As Object, str$, str1 As String, i As Integer
Set cn = CreateObject("ADODB.Connection")
Set cat = CreateObject("ADOX.Catalog")
Set tbl = CreateObject("ADOX.Table")
Set rst = CreateObject("ADODB.Recordset")
With cn
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.FullName & _
";Extended Properties=""Excel 8.0;HDR=Yes;"";"
.Open
End With
cat.ActiveConnection = cn
For Each tbl In cat.Tables
If Right(Replace(tbl.Name, "'", ""), 1) = "$" Then
str = str & " union all SELECT * from [" & _
Replace(Replace(tbl.Name, "$", ""), "'", "") & "$A1:A1000] where ma is not null"
str1 = Right(str, Len(str) - 10)
End If
Next
str1 = "select ma as Ma1, count(ma) as Dem from (" & str1 & ") group by ma"
With rst
.ActiveConnection = cn
.Open str1
End With
For Each fld In rst.Fields
i = i + 1
Cells(1, 254 + i) = fld.Name
Next
With Sheets("Sheet1")
.[IU2:IV5000].ClearContents
.[IU2].CopyFromRecordset rst
cn.Execute "UPDATE [Sheet1$A1:B6000] a " _
& "INNER JOIN " _
& "[Excel 8.0;HDR=Yes;IMEX=2;DATABASE=" & ThisWorkbook.FullName & "].[Sheet1$IU1:IV6000] b " _
& "ON a.ma=b.Ma1 " _
& "SET a.Dem=b.Dem"
.[IU1:IV5000].ClearContents
End With
rst.Close: Set rst = Nothing
cn.Close: Set cn = Nothing
Set cat = Nothing: Set tbl = Nothing
End Sub
[/GPECODE]