Option Explicit
Sub Delete_Rows_From_CSV_Files()
Dim source_folder_name As String
source_folder_name = "C:\Users\Siraj\Documents\CSV FILES\" 'change the path to the source folder accordingly
If Right(source_folder_name, 1) <> "\" Then
source_folder_name = source_folder_name & "\"
End If
If Len(source_folder_name) = 0 Then
MsgBox "The path to the source folder is invalid!", vbExclamation, "Invalid Path"
Exit Sub
End If
Application.ScreenUpdating = False
Dim rows_to_delete As Variant
rows_to_delete = Array("SM", "BE") 'change and/or add row headers as desired
Dim current_filename As String
current_filename = Dir(source_folder_name & "*.csv", vbNormal)
Dim file_count As Long
While Len(current_filename) > 0
file_count = file_count + 1
Delete_rows_from_CSV_File source_folder_name & current_filename, rows_to_delete
current_filename = Dir
Wend
Application.ScreenUpdating = True
MsgBox "Number of files processed: " & file_count, vbInformation, "Files Processed"
End Sub
Private Sub Delete_rows_from_CSV_File(ByVal source_filename As String, ByVal rows_to_delete As Variant)
Dim source_workbook As Workbook
Set source_workbook = Workbooks.Open(Filename:=source_filename)
Dim source_worksheet As Worksheet
Set source_worksheet = source_workbook.Worksheets(1)
Dim row_found As Range
Dim i As Long
For i = LBound(rows_to_delete) To UBound(rows_to_delete)
Set row_found = source_worksheet.Columns(2).Find(what:=rows_to_delete(i), LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
If Not row_found Is Nothing Then
row_found.EntireRow.Delete
End If
Next i
source_workbook.Close SaveChanges:=True
End Sub
大家好,我正在寻找一个 VBA 代码,它可以根据条件从文件夹中的所有 CSV 文件中删除多行。请帮忙。