1/ File không mở được vì cái "đuôi" của nó phải là .xls (Sao mình đổi thành *.xlsx vậy ta?)Tôi cần lọc theo danh sách đơn vị (cột O), đối với mỗi đơn vị thì xuất ra 1 file có tên tương ứng với tên đơn vị đó.
Bạn nào giúp mình cái code với.
Xin cảm ơn.
Bạn thử file sau, mình lưu file của bạn thành .xlsm và thêm Sheet("Main") để chay Macro.
Sau khi chạy nó sẽ tạo 1 sheet("log") để biết vị trí các file vừa lọc.
Mã:Public Sub GPE() Dim Dic As Object, Tmp As String, Arr, Path, Rng As Range Dim WbMain As Workbook, Ws As Worksheet, I As Long Application.ScreenUpdating = False Application.DisplayAlerts = False Application.SheetsInNewWorkbook = 1 Set WbMain = ThisWorkbook: Path = WbMain.Path Set Ws = WbMain.Sheets("LOAI 1") Set Rng = Ws.Range("A1").CurrentRegion Arr = Rng.Value Set Dic = CreateObject("Scripting.Dictionary") For I = 2 To UBound(Arr) If Arr(I, 15) <> Empty Then Tmp = Arr(I, 15) If Not Dic.Exists(Tmp) Then Dic.Add Tmp, "" With Workbooks.Add Rng.AutoFilter 15, Tmp Ws.Range("A1", Rng).SpecialCells(12).Copy .Sheets(1).Range("A1").PasteSpecial xlPasteColumnWidths .Sheets(1).Range("A1").PasteSpecial xlPasteValues .Sheets(1).Range("A1").PasteSpecial xlPasteFormats .Close True, Path & "\" & Tmp & ".xls" End With End If End If Next Ws.AutoFilterMode = False Set Dic = Nothing MsgBox "Done!" Application.SheetsInNewWorkbook = 3 Application.CutCopyMode = False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub
eo! sao anh không sort dữ liệu cho nhanh, khi đó không cần dic, không cần autofilter. chỉ cần duyệt mảng đếm phần tử là có thể xuất dữ liệu rồi. Bạn ý kêu là còn nhiều file sẽ xuất từ phần mềm trong tương lai nữa. Vậy có nên chăng chơi kiểu macro viết trên một file, khi cần tách thì mở file cần tách. chạy macro thì cho phép người dùng bấm chuột vào sheet cần tách. Hoặc một cách tương tự nào đó.Mã:Public Sub GPE() Dim Dic As Object, Tmp As String, Arr, Path, Rng As Range Dim WbMain As Workbook, Ws As Worksheet, I As Long Application.ScreenUpdating = False Application.DisplayAlerts = False Application.SheetsInNewWorkbook = 1 Set WbMain = ThisWorkbook: Path = WbMain.Path Set Ws = WbMain.Sheets("LOAI 1") Set Rng = Ws.Range("A1").CurrentRegion Arr = Rng.Value Set Dic = CreateObject("Scripting.Dictionary") For I = 2 To UBound(Arr) If Arr(I, 15) <> Empty Then Tmp = Arr(I, 15) If Not Dic.Exists(Tmp) Then Dic.Add Tmp, "" With Workbooks.Add Rng.AutoFilter 15, Tmp Ws.Range("A1", Rng).SpecialCells(12).Copy .Sheets(1).Range("A1").PasteSpecial xlPasteColumnWidths .Sheets(1).Range("A1").PasteSpecial xlPasteValues .Sheets(1).Range("A1").PasteSpecial xlPasteFormats .Close True, Path & "\" & Tmp & ".xls" End With End If End If Next Ws.AutoFilterMode = False Set Dic = Nothing MsgBox "Done!" Application.SheetsInNewWorkbook = 3 Application.CutCopyMode = False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub