Sub main()
Dim i As Long, rend As Long, j As Long
Dim cend As Integer, cendtem As Integer
Dim arr 'Vung data tu cot V toi cot cuoi,tu dong rtitle toi rend
Dim crr 'Luu cong thuc
Dim Rng As Range
Dim flag1 As Boolean 'Phat hien san pham
Dim slcl As Double 'So luong con lai, cot V
Dim d As Double 'Du lieu dong rtitle
Dim checkrr
Const cV As Integer = 22 'Cot V
Const cW As Integer = 23 'Cot W chua cong thuc -vbano1 website tuhocvba.net
Const rtitle As Long = 3 'Dong chua thong tin ke hoach san xuat
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Xac dinh dong cuoi tren cot V
rend = ThisWorkbook.ActiveSheet.Cells(Rows.Count, cV).End(xlUp).Row
If rend <= rtitle + 1 Then
MsgBox "Khong co du lieu"
GoTo thoat
End If
'Xac dinh cot cuoi tren dong rtitle
cendtem = 0
For i = rtitle To rend Step 1
cend = ThisWorkbook.ActiveSheet.Cells(i, Columns.Count).End(xlToLeft).Column
If cend > cendtem Then
cendtem = cend
End If
Next i
cend = cendtem
If cend <= cV + 1 Then
MsgBox "Khong co du lieu"
GoTo thoat
End If
arr = ThisWorkbook.ActiveSheet.Range(Cells(rtitle, cV), Cells(rend, cend)).Value
Set Rng = ThisWorkbook.ActiveSheet.Range(Cells(rtitle, cW), Cells(rend, cW))
ReDim crr(1 To rend - rtitle + 1)
Call luucongthuc(Rng, crr)
flag1 = False
For i = LBound(arr, 1) To UBound(arr, 1) Step 1
'V3 = "" and W3 <> ""
If (Trim(CStr(arr(i, 1))) = "") And (Trim(CStr(arr(i, 2))) <> "") Then
'Phat hien san pham
flag1 = True
slcl = 0
checkrr = ThisWorkbook.ActiveSheet.Range(Cells(rtitle + i - 1, cV), Cells(rtitle + i - 1, cend)).Value
Else
flag1 = False
End If
If flag1 = False Then
slcl = kiemtraso(Trim(CStr(arr(i, 1)))) + slcl 'Cot V
For j = 3 To UBound(arr, 2) Step 1 'Chay tu cot X toi cot cuoi
If slcl <= 0 Then Exit For 'Khong con kha nang cung ung
d = 0 'Du lieu dong rtile
If Trim(CStr(checkrr(1, j))) <> "" Then
If IsNumeric(Trim(CStr(checkrr(1, j)))) Then d = kiemtraso(Trim(CStr(checkrr(1, j))))
If d > 0 Then
If d <= slcl Then
arr(i, j) = d
slcl = slcl - d
checkrr(1, j) = 0
Else
arr(i, j) = slcl
checkrr(1, j) = d - slcl
slcl = 0
End If
End If
End If
Next j
End If
Next i
ThisWorkbook.ActiveSheet.Range(Cells(rtitle, cV), Cells(rend, cend)).Value = arr
Call tralaicongthuc(Rng, crr)
thoat:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
'Not Number: -1111111
'Number: 0,1,2,...
Function kiemtraso(ByVal s As String) As Double
If s = "" Then
kiemtraso = -1111111
Exit Function
End If
If IsNumeric(s) = False Then
kiemtraso = -1111111
Else
kiemtraso = CDbl(s)
End If
End Function
Sub luucongthuc(ByVal Rng As Range, ByRef crr As Variant)
Dim cnt As Long
Dim congthuc As String
Dim rr As Range
cnt = 0
For Each rr In Rng
cnt = cnt + 1
If rr.HasFormula = True Then
crr(cnt) = rr.Formula
Else
crr(cnt) = ""
End If
Next
End Sub
Sub tralaicongthuc(ByVal Rng As Range, ByRef crr As Variant)
Dim rr As Range
Dim cnt As Long
cnt = 0
For Each rr In Rng
cnt = cnt + 1
If CStr(crr(cnt)) <> "" Then
rr.Formula = CStr(crr(cnt))
End If
Next
End Sub