Option Explicit
Public Function LastRowInOneColumn(ByVal sheet As Worksheet, ByVal sCol As String)
Dim lstobj As Object
With sheet
For Each lstobj In .ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter
lstobj.Range.AutoFilter
End If
Next lstobj
If .AutoFilterMode = True Then .AutoFilterMode = False
LastRowInOneColumn = .Cells(.Rows.Count, sCol).End(xlUp).Row
End With
End Function
Public Function LastColumnInOneRow(ByVal sheet As Worksheet, ByVal iRow As Long)
Dim lstobj As Object
With sheet
For Each lstobj In .ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter
lstobj.Range.AutoFilter
End If
Next lstobj
If .AutoFilterMode = True Then .AutoFilterMode = False
LastColumnInOneRow = .Cells(iRow, .Columns.Count).End(xlToLeft).Column
End With
End Function
Sub Test()
Dim dict As Object
Dim shTGGH As Worksheet, shKH As Worksheet
Dim Data As Variant, Result As Variant
Dim sKEY As String
Dim c As Long, r As Long, i As Long, j As Long
Dim orderDate As Date
Dim dbQuantity As Double
Const DELIM = "|"
Set shTGGH = ThisWorkbook.Worksheets("TG GH")
Set shKH = ThisWorkbook.Worksheets("KH")
r = LastRowInOneColumn(shKH, "H")
c = LastColumnInOneRow(shKH, 10)
If (r < 11) Or (c < 21) Then
MsgBox "Du lieu khong phu hop,hay kiem tra lai sheet " & shKH.Name, _
vbCritical + vbOKOnly
Exit Sub
End If
Result = shKH.Range("A10:A" & r).Resize(, c).Value
r = LastRowInOneColumn(shTGGH, "J")
If (r < 11) Then
MsgBox "Du lieu khong phu hop,hay kiem tra lai sheet " & shTGGH.Name, _
vbCritical + vbOKOnly
Exit Sub
End If
Data = shTGGH.Range("A11:Q" & r).Value
Set dict = CreateObject("Scripting.Dictionary")
For j = 21 To UBound(Result, 2)
If IsDate(Result(1, j)) Then
orderDate = Result(1, j)
If Not dict.Exists(orderDate) Then dict.Add orderDate, j
End If
Next j
For i = 2 To UBound(Result, 1) Step 3
sKEY = Join(Array(Result(i, 2), Result(i, 7), Result(i, 8)), DELIM)
If Not dict.Exists(sKEY) Then dict.Add sKEY, i
Result(i, 19) = Empty
For j = 21 To UBound(Result, 2)
Result(i, j) = Empty
Next j
Next i
For i = LBound(Data, 1) To UBound(Data, 1)
sKEY = Join(Array(Data(i, 2), Data(i, 5), Data(i, 10)), DELIM)
orderDate = Data(i, 12): dbQuantity = Data(i, 17)
r = dict.Item(sKEY): c = dict.Item(orderDate)
If (r > 0) And (c > 0) Then
Result(r, c) = Result(r, c) + dbQuantity
Result(r, 19) = Result(r, 19) + dbQuantity
End If
Next i
shKH.Range("A10").Resize(UBound(Result, 1), UBound(Result, 2)).Value = Result
MsgBox "Xong roi!", vbInformation + vbOKOnly
End Sub