А это должно работать для массовой обработки всех файлов xlsx в папке на всех листах
| Код |
|---|
Sub ApplyMacroToAllFiles()
Dim folderPath As String
Dim fileName As String
Dim ws As Worksheet
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then
folderPath = .SelectedItems(1)
Else
MsgBox "Folder selection canceled.", vbExclamation
Exit Sub
End If
End With
On Error Resume Next
fileName = Dir(folderPath & "\*.xlsx")
Do While fileName <> ""
Workbooks.Open folderPath & "\" & fileName
For Each ws In ActiveWorkbook.Sheets
RemoveEmptyRows ws
Next ws
ActiveWorkbook.Close SaveChanges:=True
fileName = Dir
Loop
On Error GoTo 0
End Sub
Sub RemoveEmptyRows(ws As Worksheet)
Dim rng As Range
Dim i As Long
Dim selectedColumns As Range
Dim selectedColumn As Range
Dim nonEmptyRows As Range
Dim destinationSheet As Worksheet
Dim destinationRow As Long
Dim area As Range
Set ws = ws
On Error Resume Next
Set selectedColumns = Application.InputBox("Select the range of columns (use your mouse to select)", Type:=8)
On Error GoTo 0
If selectedColumns Is Nothing Then
MsgBox "You did not select a range of columns. The code will be applied to column A.", vbInformation
Set selectedColumns = ws.Columns("A")
End If
For Each selectedColumn In selectedColumns.Columns
Set rng = ws.Columns(selectedColumn.Column)
For i = 1 To rng.Rows.Count
If Application.WorksheetFunction.CountA(rng.Rows(i)) <> 0 Then
If nonEmptyRows Is Nothing Then
Set nonEmptyRows = rng.Rows(i)
Else
Set nonEmptyRows = Union(nonEmptyRows, rng.Rows(i))
End If
End If
Next i
Next selectedColumn
Set destinationSheet = Worksheets.Add
destinationSheet.Name = "Result (" & Format(Now, "yyyymmdd_hhmmss") & ")"
destinationRow = 1
For Each area In nonEmptyRows.Areas
area.Copy Destination:=destinationSheet.Cells(destinationRow, 1)
destinationRow = destinationRow + area.Rows.Count
Next area
End Sub |
Изменено: - 04.12.2023 17:50:43