简体   繁体   中英

Excel VBA: Delete blank columns & entire rows if specific columns are blank on specific worksheet not working

My problem is the macro won't work on a specified worksheet, only the active one. I have two subroutines for deleting entire columns, and then deleting entire rows if specific columns are blank. I want to make it work for a specific worksheet, which I understood to be With Worksheets("OutPut") but it still culls the active worksheet.

It works as intended so long as the active worksheet is selected.

Sub DeleteBlankColumns()
    With Worksheets("OutPut")
        Set MyRange = Worksheets("OutPut").UsedRange
        For iCounter = MyRange.Columns.Count To 1 Step -1
            If Application.CountA(Columns(iCounter).EntireColumn) = 0 Then
            Columns(iCounter).Delete
            End If
        Next iCounter
        End With
End Sub

And

Sub QuickCull()
    With Worksheets("OutPut")
        On Error Resume Next
        Columns("B").SpecialCells(xlBlanks).EntireRow.Delete
        On Error Resume Next
        Columns("C").SpecialCells(xlBlanks).EntireRow.Delete
        On Error Resume Next
        Columns("D").SpecialCells(xlBlanks).EntireRow.Delete
        On Error Resume Next
        Columns("E").SpecialCells(xlBlanks).EntireRow.Delete
        End With
End Sub

There's a button to Call both of them, which again, will work if the worksheet I want to transform is active. For reference, this is intended to be appended on an existing company macro, so simply running it on the worksheet when it's active won't work.

Thank you!

For the first code sample,

If Application.CountA(Columns(iCounter).EntireColumn) = 0 Then
     Columns(iCounter).Delete

should be

If Application.CountA(.Columns(iCounter).EntireColumn) = 0 Then
     .Columns(iCounter).Delete

(a "." before Columns, to specify the sheet)

Same thing for the second code sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM