Private Sub Worksheet_Change(ByVal Target As Range)
' ta chi phuc vu su thay doi trong cot M de tinh cot B va A. Code chi phuc vu su thay doi cua 1 o
' trong cot M o moi thoi diem. Neu co nhu cau dan 1 lan hang loat gia tri vao cot M thi phai sua lai code
Dim lastRow As Long, r As Long, number As Long, cotB(), nhiemvuchi, ctmt As Long
If Target.Count <> 1 Or Target.Column <> 13 Then Exit Sub
' de khong say ra su kien Change khi code thay doi cot B va A
Application.EnableEvents = False
' tinh cot B
If Target.Offset(0, 1).Value = "00000" Then
nhiemvuchi = Application.VLookup(Target.Value, Sheet7.Range("N4:Q144"), 3, 0)
Else
ctmt = CLng(Target.Offset(0, 1).Value)
nhiemvuchi = Application.VLookup(ctmt, Sheet7.Range("J4:L144"), 3, 0)
End If
If IsError(nhiemvuchi) Then
' khong tim thay Ma so. Nhap "cha co gi" vao cot B. O trong cot M dich sang trai 11 o thi la o trong cot B
Target.Offset(, -11).Value = Empty
Else
' tim thay Ma so nhiemvuchi
Target.Offset(, -11).Value = nhiemvuchi
End If
' tinh cot A
With Me
lastRow = .Cells(Rows.Count, "M").End(xlUp).Row
If lastRow >= 6 Then
' cot M co du lieu -> nhap cot B vao mang cotB
cotB = .Range("B6:B" & lastRow + 1).Value
' duyet tung o cua mang cotB
For r = 1 To UBound(cotB)
If cotB(r, 1) <> "" Then
' o co gia tri, vay thay bang so thu tu lien tiep number
number = number + 1
cotB(r, 1) = number
End If
Next r
' nhap mang cotB chua STT hoac rong vao cot A
.Range("A6").Resize(UBound(cotB)).Value = cotB
End If
End With
Application.EnableEvents = True
End Sub