Option Explicit Sub TachPhongBan() Dim oDoc As Object Dim oSheets As Object Dim oSource As Object Dim oTarget As Object Dim lastRow As Long Dim lastCol As Long Dim r As Long Dim c As Long Dim dept As String Dim targetRow As Long oDoc = ThisComponent oSheets = oDoc.Sheets oSource = oDoc.CurrentController.ActiveSheet 'Tìm dòng cuối lastRow = 4 Do While oSource.getCellByPosition(0, lastRow).String <> "" lastRow = lastRow + 1 Loop lastRow = lastRow - 1 'Tìm cột cuối lastCol = 0 Do While oSource.getCellByPosition(lastCol, 3).String <> "" lastCol = lastCol + 1 Loop lastCol = lastCol - 1 For r = 4 To lastRow dept = Trim(oSource.getCellByPosition(4, r).String) If dept <> "" Then If Not oSheets.hasByName(dept) Then oSheets.insertNewByName(dept, oSheets.Count) oTarget = oSheets.getByName(dept) 'Copy tiêu đề (dòng 4) oTarget.copyRange( _ oTarget.getCellByPosition(0, 0).CellAddress, _ oSource.getCellRangeByPosition(0, 3, lastCol, 3).RangeAddress) 'Copy độ rộng cột For c = 0 To lastCol oTarget.Columns.getByIndex(c).Width = _ oSource.Columns.getByIndex(c).Width Next c Else oTarget = oSheets.getByName(dept) End If targetRow = 1 Do While oTarget.getCellByPosition(0, targetRow).String <> "" targetRow = targetRow + 1 Loop 'Copy nguyên dòng (giữ định dạng) oTarget.copyRange( _ oTarget.getCellByPosition(0, targetRow).CellAddress, _ oSource.getCellRangeByPosition(0, r, lastCol, r).RangeAddress) End If Next r MsgBox "Hoàn thành" End Sub