Sub AccToEx_2()
If AccConn = False Then
MsgBox "Khong ket noi"
GoTo ErrorHandle
End If
Dim sSQL As String
Dim adoCommand As Object, oRs As Object
gcnObj.Open
sSQL = "SELECT MaNV, TenNV, Thang, SUM(SoLuong) As TongSoLuong, NoiLamViec As DienGiai " _
& "FROM NhanVien WHERE Thang = 'THÁNG 07/ 2012' " _
& "GROUP BY MaNV, TenNV, Thang, NoiLamViec;"
Set adoCommand = CreateObject("ADODB.Command")
With adoCommand
.CommandType = 1
.ActiveConnection = gcnObj
.CommandText = sSQL
End With
Set oRs = CreateObject("ADODB.Recordset")
oRs.Open adoCommand, , 3, 4
If oRs.EOF Then
MsgBox "Không có records nào!", vbOKOnly + vbInformation, "THÔNG BÁO"
GoTo ErrHandle
End If
Dim AccessArr, AcToExArr, ExcelArr, ArrField()
Dim c As Long, h As Long, i As Long, j As Long, n As Long, r As Long
Dim tmp As String: tmp = ""
[COLOR=#008000] ''*****Lay FiledsName -> ArrField:[/COLOR]
n = oRs.Fields.Count
ReDim ArrField(1 To n)
For c = 1 To n
ArrField(c) = oRs.Fields(c - 1).Name
Next
[COLOR=#008000] ''*****Lay Array tu Access:[/COLOR]
AccessArr = oRs.GetRows
c = UBound(AccessArr, 1) + 1
h = UBound(AccessArr, 2) + 1
ReDim AcToExArr(1 To h, 1 To c)
For i = 1 To h
For j = 1 To c
AcToExArr(i, j) = AccessArr(j - 1, i - 1)
Next
Next
[COLOR=#008000]''****Xu ly cong group AcToExArr -> ExcelArr:[/COLOR]
[COLOR=#0000cd] [B] ReDim ExcelArr(1 To h, 1 To c): r = 0
For i = 1 To h
If AcToExArr(i, 1) <> tmp Then
r = r + 1
For c = 1 To 4
ExcelArr(r, c) = AcToExArr(i, c)
Next
ExcelArr(r, 5) = AcToExArr(i, 5) & " (" & AcToExArr(i, 4) & ")" [/B][/COLOR][COLOR=#008000][B]''DienGiai[/B][/COLOR][COLOR=#0000cd][B]
Else
ExcelArr(r, 4) = ExcelArr(r, 4) + AcToExArr(i, 4) [/B][/COLOR][COLOR=#008000][B]''SoLuong[/B][/COLOR][COLOR=#0000cd][B]
ExcelArr(r, 5) = ExcelArr(r, 5) & "; " & AcToExArr(i, 5) & " (" & AcToExArr(i, 4) & ")" [/B][/COLOR][COLOR=#008000][B]''DienGiai[/B][/COLOR][COLOR=#0000cd][B]
End If
tmp = AcToExArr(i, 1)
Next[/B]
[/COLOR]
With Sheets("Report")
.Cells.ClearContents
.Range("A1").Resize(, 5) = ArrField
.Range("A2").Resize(r, 5) = ExcelArr
End With
Erase AccessArr, AcToExArr, ExcelArr, ArrField()
ErrHandle:
Set adoCommand = Nothing
Set oRs = Nothing
ErrorHandle:
If Not gcnObj Is Nothing Then
If (gcnObj.State And adStateOpen) = adStateOpen Then
gcnObj.Close
End If
Set gcnObj = Nothing
End If
End Sub