Xóa dòng các file trong thư mục

Liên hệ QC
Tôi tuân thủ nội quy khi đăng bài
nhưng bây giờ em muốn chọn nhiều thư mục một lần..
Mình chưa hiểu cách mà bạn chọn nhiều thư mục một lần là làm như thế nào.
Mà mình thấy yêu cầu trong khả năng nên chỉ tham gia góp vui theo thôi bạn còn thêm thêm gì nữa thì có lẽ vượt khả năng của mình rồi ...
 
Mình chưa hiểu cách mà bạn chọn nhiều thư mục một lần là làm như thế nào.
Mà mình thấy yêu cầu trong khả năng nên chỉ tham gia góp vui theo thôi bạn còn thêm thêm gì nữa thì có lẽ vượt khả năng của mình rồi ...
folderPath = "C:\Users\OT\Desktop\Folder\" 'Duong dan thu muc chua file excel
Em muốn thêm thư mục như này mà không được chị oi
folderPath = "C:\Users\admin\Desktop\New folder" And folderPath = "C:\Users\admin\Desktop\New folder2" 'Duong dan thu muc chua file excel"
 
Em muốn thêm thư mục như này mà không được chị oi
folderPath = "C:\Users\admin\Desktop\New folder" And folderPath = "C:\Users\admin\Desktop\New folder2" 'Duong dan thu muc chua file excel"
Mình không có nhu cầu nên không giả lập môi trường test,
bạn tham khảo hên thì được còn xui thì thôi nha :
Mã:
Option Explicit

Sub deleteRows()

    Dim folderName As Variant, folder As Variant
    Dim count As Long
    folderName = Array("C:\Users\admin\Desktop\New folder", "C:\Users\admin\Desktop\New folder2")
    For Each folder In folderName
        count = count + FdeleteRows(folder, "Nguon", "5:8")
    Next folder
    MsgBox count & " File(s) Amended"
   
End Sub

Function FdeleteRows(ByVal folderPath As String, ByVal shName As String, ByVal rowNums As String) As Long

    Dim fso As Object, folder As Object, file As Object
    Dim wb As Workbook, ws As Worksheet

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(folderPath)

    For Each file In folder.Files
    If LCase(file.Name) Like "*.xls*" Then
        Set wb = Workbooks.Open(file.Path)
        On Error Resume Next
        Set ws = wb.Worksheets(shName)
        On Error GoTo 0
        If Not ws Is Nothing Then
            Application.DisplayAlerts = False
            ws.Rows(rowNums).Delete Shift:=xlUp
            Application.DisplayAlerts = True
            wb.Save
            FdeleteRows = FdeleteRows + 1
        End If
        wb.Close False
    End If
    Next file

End Function
 
Mình không có nhu cầu nên không giả lập môi trường test,
bạn tham khảo hên thì được còn xui thì thôi nha :
Mã:
Option Explicit

Sub deleteRows()

    Dim folderName As Variant, folder As Variant
    Dim count As Long
    folderName = Array("C:\Users\admin\Desktop\New folder", "C:\Users\admin\Desktop\New folder2")
    For Each folder In folderName
        count = count + FdeleteRows(folder, "Nguon", "5:8")
    Next folder
    MsgBox count & " File(s) Amended"
  
End Sub

Function FdeleteRows(ByVal folderPath As String, ByVal shName As String, ByVal rowNums As String) As Long

    Dim fso As Object, folder As Object, file As Object
    Dim wb As Workbook, ws As Worksheet

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(folderPath)

    For Each file In folder.Files
    If LCase(file.Name) Like "*.xls*" Then
        Set wb = Workbooks.Open(file.Path)
        On Error Resume Next
        Set ws = wb.Worksheets(shName)
        On Error GoTo 0
        If Not ws Is Nothing Then
            Application.DisplayAlerts = False
            ws.Rows(rowNums).Delete Shift:=xlUp
            Application.DisplayAlerts = True
            wb.Save
            FdeleteRows = FdeleteRows + 1
        End If
        wb.Close False
    End If
    Next file

End Function
Em cảm ơn chị rất nhiều ạ, để chiều em về Test xem sao, em tin chắc là được.
 
Em cảm ơn chị @Hoàng Nhật Phương ạ code chạy rất chuẩn chị oi
Nhưng bây giờ em muốn chọn nhiều thư mục một lần thì thêm như nào hở chị?
Bài đã được tự động gộp:


Em cảm ơn anh @THÓC SAMA code đúng theo ý tưởng của em là cho vào thư mục cần xóa để đỡ nhầm lẫn anh ah
Anh chỉnh cho em là code đọc được cả file tiếng việt như anh @Hoàng Tuấn 868 góp ý với anh nhé
Em cảm ơn anh.
Của bạn đây, vẫn là con Gấu khóc nhiều
Mã:
Sub ABC()
    Dim MyFolder As String, MyFile As String
    Dim MainWB As Workbook, Wb As Workbook
    Dim Ws As Worksheet, a%
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False
    Application.Calculation = xlCalculationManual
    Set MainWB = ThisWorkbook
    MyFolder = ThisWorkbook.Path
    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set MyFolderObj = Fso.GetFolder(MyFolder)
    Dim FileNum%
    FileNum = 1
    For Each MyFileObj In MyFolderObj.Files
        If InStr(MyFileObj.Name, ".xlsx") > 0 Then
            If MyFileObj.Name <> MainWB.Name Then
                If FileNum = a + 1 Then
                    MyFile = MyFileObj.Name
                    Workbooks.Open FileName:=MyFolder & "\" & MyFile
                    Set Wb = ActiveWorkbook
                    With Wb
                        For Each Ws In .Worksheets
                            If Ws.Name = "Nguon" Then Rows("5:8").Delete
                        Next
                    End With
                    a = a + 1
                    Wb.Close True
                End If
                FileNum = FileNum + 1
            End If
        End If
    Next MyFileObj
    MsgBox "Done"
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True
    Application.Calculation = xlCalculationAutomatic
End Sub
 

File đính kèm

  • MAIN_FILE.xlsb
    17 KB · Đọc: 4
Sao bài của tớ tên tập tin bằng tiếng gì nó cũng nhai hết nhỉ.
Code bác "ăn tạp" quá chăng?
...
Tôi nhớ hình như nhược điểm của DIR là nó không thích tiếng có dấu (tiếng Việt, Pháp,... gì cũng không được).

Mình không có nhu cầu nên không giả lập môi trường test,
bạn tham khảo hên thì được còn xui thì thôi nha :
...
Sub deleteRows()
Dim thefolder As Variant
Dim countFolders As Long, countFiles As Long
For Each thefolder In Array("C:\Users\admin\Desktop\New folder", "C:\Users\admin\Desktop\New folder2")
countFiles = countFiles + FdeleteRows(thefolder, "Nguon", "5:8")
countFolders = countFolders + 1
Next folder
MsgBox countFiles & " File(s) from " & countFolders & " folders Amended"
End Sub

Chú về thefolder, countFolders, countFiles:
Khi viết code, cố tránh những tên quá đơn giản mà rõ rệt (files, folders, count,...). Bởi vì chúng dễ bị đụng chạm với các code ngầm, hoặc các Enums trong hệ thống. Hôm nay code của bạn có thể suông sẻ nhưng ngày mai, bạn reference một cái thư viện nào đó biết đâu sẽ bị chạm tên.

Chú 2:
Nếu một ngày nào đó, code của bạn bị chạm tên khi đưa vào phiên bản mới của Excel, hãy nhớ lời chú trên. Tìm trong code có những tên đơn giản mà rõ rệt thì 95% là thủ phạm.
 
Của bạn đây, vẫn là con Gấu khóc nhiều
Mã:
Sub ABC()
    Dim MyFolder As String, MyFile As String
    Dim MainWB As Workbook, Wb As Workbook
    Dim Ws As Worksheet, a%
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False
    Application.Calculation = xlCalculationManual
    Set MainWB = ThisWorkbook
    MyFolder = ThisWorkbook.Path
    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set MyFolderObj = Fso.GetFolder(MyFolder)
    Dim FileNum%
    FileNum = 1
    For Each MyFileObj In MyFolderObj.Files
        If InStr(MyFileObj.Name, ".xlsx") > 0 Then
            If MyFileObj.Name <> MainWB.Name Then
                If FileNum = a + 1 Then
                    MyFile = MyFileObj.Name
                    Workbooks.Open FileName:=MyFolder & "\" & MyFile
                    Set Wb = ActiveWorkbook
                    With Wb
                        For Each Ws In .Worksheets
                            If Ws.Name = "Nguon" Then Rows("5:8").Delete
                        Next
                    End With
                    a = a + 1
                    Wb.Close True
                End If
                FileNum = FileNum + 1
            End If
        End If
    Next MyFileObj
    MsgBox "Done"
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True
    Application.Calculation = xlCalculationAutomatic
End Sub
Tôi thấy 2 biến FileNum và a của bạn có vẻ thừa thừa.
 
Không biết chỉnh lý lại thì có cần hay không chứ trong code trên thiếu nó là không được bác à.
Bạn bỏ cả 2 biến và cái if FileNum = a + 1 đi thử xem. Lý do:

Đầu tiên tất nhiên là đúng rồi vì khi đó FileNum = 1 và a = 0. Khi 2 if bên trên thoả thì tất nhiên a cộng thêm 1 và tiếp đó FileNum cũng cộng thêm 1. Các chu kỳ sau đó cứ mỗi biến lại thêm 1 thì if FileNum = a + 1 luôn luôn thỏa mà.

Không biết tôi có đọc sót chỗ nào không?
 
Của bạn đây, vẫn là con Gấu khóc nhiều
Mã:
Sub ABC()
    Dim MyFolder As String, MyFile As String
    Dim MainWB As Workbook, Wb As Workbook
    Dim Ws As Worksheet, a%
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False
    Application.Calculation = xlCalculationManual
    Set MainWB = ThisWorkbook
    MyFolder = ThisWorkbook.Path
    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set MyFolderObj = Fso.GetFolder(MyFolder)
    Dim FileNum%
    FileNum = 1
    For Each MyFileObj In MyFolderObj.Files
        If InStr(MyFileObj.Name, ".xlsx") > 0 Then
            If MyFileObj.Name <> MainWB.Name Then
                If FileNum = a + 1 Then
                    MyFile = MyFileObj.Name
                    Workbooks.Open FileName:=MyFolder & "\" & MyFile
                    Set Wb = ActiveWorkbook
                    With Wb
                        For Each Ws In .Worksheets
                            If Ws.Name = "Nguon" Then Rows("5:8").Delete
                        Next
                    End With
                    a = a + 1
                    Wb.Close True
                End If
                FileNum = FileNum + 1
            End If
        End If
    Next MyFileObj
    MsgBox "Done"
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True
    Application.Calculation = xlCalculationAutomatic
End Sub
Em chúc anh ngày mới an lành và nhiều niềm vui hạnh phúc ạ
Anh oi, anh xem lại giúp em với anh
Code không xóa được anh oi
 
Em chúc anh ngày mới an lành và nhiều niềm vui hạnh phúc ạ
Anh oi, anh xem lại giúp em với anh
Code không xóa được anh oi
Bạn có thể chụp màn hình báo lỗi gửi lên đây được không?
Theo kết quả test code của mình thì code chạy rất "nhiệt tình".
Hình phía dưới là folder chứa file Main (gán code) và các files cần xoá dòng của bạn ở #1.
Bạn tải file main đính kèm về, để chung thư mục với các files cần xoá dòng và chạy code thử xem nha.
Nếu được, bạn gửi luôn đường dẫn folder đang sử dụng lên nha!
1681178992396.png
 

File đính kèm

  • MAIN_FILE.xlsb
    17 KB · Đọc: 3
Em muốn thêm thư mục như này mà không được chị oi
folderPath = "C:\Users\admin\Desktop\New folder" And folderPath = "C:\Users\admin\Desktop\New folder2" 'Duong dan thu muc chua file excel"
Không biết trên máy khác ra sao chứ trên máy của tôi code (theo gợi ý của Anh @ptm0412) thì thấy chạy cũng êm, nhưng không biết khi chạy code này có gì không ổn không. Nhờ các anh, chị, em thành viên ghé xem và khai sáng cho tôi các vấn đề bất ổn khi sử dụng code này.
Trân trọng cảm ơn!
Mã:
Option Explicit

Sub XoaDong()

Dim oFile As Variant, afol
Dim fso As Object, Path As String
Dim WbMo As Workbook, i&

Application.DisplayAlerts = False

Set fso = CreateObject("Scripting.FileSystemObject")

Path = ThisWorkbook.Path
afol = Array(, Path & "\New folder1", Path & "\New folder2")

For i = 1 To UBound(afol)
    For Each oFile In fso.GetFolder(afol(i)).Files
        Set WbMo = Workbooks.Open(oFile)
        On Error Resume Next
        If ShExist(ActiveWorkbook, "Nguon") = True Then
            Sheets("Nguon").Rows("3:8").EntireRow.Delete
        End If
    WbMo.Close True
    Next oFile
Next i
Application.DisplayAlerts = True
End Sub

Function ShExist(ByVal wb As Workbook, ByVal shName As String) As Boolean
Dim Sh As Worksheet
ShExist = False
For Each Sh In wb.Sheets
    If Sh.Name = shName Then ShExist = True: Exit For
Next
End Function
 

File đính kèm

  • HongPhuong.rar
    216.6 KB · Đọc: 2
Chỗ:
afol = Array(, Path & "\New folder1", Path & "\New folder2")

For i = 1 To UBound(afol)
Lần đầu tiên tôi thấy "lách" số 0 kiểu này á --=0. Cũng thú vị nhưng không đường đường chính chính lắm :D

Tôi thì tôi cứ hoặc là Option Base 1, hoặc là
afol = Array(Path & "\New folder1", Path & "\New folder2")

For i = 0 To UBound(afol)
 
PHP:
Option Explicit

Sub XoaDong()
Const strWsNameTarget = "Nguon"
Const strNameFolder1= "Folder 1"
Const strNameFolder2= "Folder 2"
Dim oFile As object, afol as variant
Dim fso As Object, strPath As String, oFolder as object
Dim WbMo As Workbook, i as long

Application.DisplayAlerts = False

Set fso = CreateObject("Scripting.FileSystemObject")

strPath= ThisWorkbook.Path
afol = Array(fso.BuildPath(strPath,  strNameFolder1), fso.BuildPath(strPath,  strNameFolder2) )

For i = lbound(afol) To UBound(afol)
set oFolder =fso.getFolder(afol(i))
if oFolder.Files.count > 0 then
    For Each oFile in InoFolder.Files
        Set WbMo = Workbooks.Open(oFile.Path)
        If isSheetExists(WbMo, strWsNameTarget) = True Then
            WbMo.Worksheets(strWsNameTarget).Rows("3:8").Delete
           WbMo.Close True
        Else
           WbMo.Close False
        End If
    Next oFile
end if
Next i
Application.DisplayAlerts = True
End Sub

Function isSheetExists(ByVal wb As Workbook, ByVal strWsName As String) As Boolean
Dim Sh As Worksheet
On Error Resume Next
set sh = wb.Worksheets(strWsName)
If Err = 0 Then isSheetExists= True Else: isSheetExists= False
On Error GoTo 0
End Function
 
Chỗ:
afol = Array(, Path & "\New folder1", Path & "\New folder2")

For i = 1 To UBound(afol)
Lần đầu tiên tôi thấy "lách" số 0 kiểu này á --=0. Cũng thú vị nhưng không đường đường chính chính lắm :D

Tôi thì tôi cứ hoặc là Option Base 1, hoặc là
afol = Array(Path & "\New folder1", Path & "\New folder2")

For i = 0 To UBound(afol)
PHP:
Option Explicit

Sub XoaDong()
Const strWsNameTarget = "Nguon"
Const strNameFolder1= "Folder 1"
Const strNameFolder2= "Folder 2"
Dim oFile As object, afol as variant
Dim fso As Object, strPath As String, oFolder as object
Dim WbMo As Workbook, i as long

Application.DisplayAlerts = False

Set fso = CreateObject("Scripting.FileSystemObject")

strPath= ThisWorkbook.Path
afol = Array(fso.BuildPath(strPath,  strNameFolder1), fso.BuildPath(strPath,  strNameFolder2) )

For i = lbound(afol) To UBound(afol)
set oFolder =fso.getFolder(afol(i))
if oFolder.Files.count > 0 then
    For Each oFile in InoFolder.Files
        Set WbMo = Workbooks.Open(oFile.Path)
        If isSheetExists(WbMo, strWsNameTarget) = True Then
            WbMo.Worksheets(strWsNameTarget).Rows("3:8").Delete
           WbMo.Close True
        Else
           WbMo.Close False
        End If
    Next oFile
end if
Next i
Application.DisplayAlerts = True
End Sub

Function isSheetExists(ByVal wb As Workbook, ByVal strWsName As String) As Boolean
Dim Sh As Worksheet
On Error Resume Next
set sh = wb.Worksheets(strWsName)
If Err = 0 Then isSheetExists= True Else: isSheetExists= False
On Error GoTo 0
End Function
Cảm ơn các anh đã xem bài và khai sáng.
 
Web KT

Bài viết mới nhất

Back
Top Bottom