简体   繁体   中英

How to delete column from range if cell contains specific value in VBA/Excel

I'm trying to write a bit of VBA which will check the value of a cell in a range of columns (rows M to GD), if the cell does not contain “YY” delete the column.

The cell to check is always in row 22

I've tried the following, but it's seriously slow.

w = 186
Do
If Worksheets(“SOF”).Cells(22, w).Formula = "YY" Then
w = w - 1
Else
   Worksheets(“SOF”).Cells(22, w).EntireColumn.Delete
End If
w = w - 1
Loop Until w < 13

Does anyone have any suggestions on how to speed this up or a better way to do this problem?

Thanks

Does anyone have any suggestions on how to speed this up or a better way to do this problem?

Yup there is. Do not delete the columns in a loop . Use the Union method. Here is an example. I have commented the code so you will not have a problem understanding it. Still if you do then simply post back.

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim i As Long
    Dim delRange As Range

    '~~> Set this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("SOF")

    With ws
        '~~> Loop through relevant columns
        For i = 13 To 186
            '~~> Check if the value is equal to YY
            If UCase(Trim(.Cells(22, i).Value)) = "YY" Then
                '~~> Store the Range to delete later
                If delRange Is Nothing Then
                    Set delRange = .Columns(i)
                Else
                    Set delRange = Union(delRange, .Columns(i))
                End If
            End If
        Next i
    End With

    '~~> Delete the relevant columns in one go
    If Not delRange Is Nothing Then delRange.Delete
End Sub

This would execute in a blink of an eye but if you want, you can sandwich the code between Application.ScreenUpdating = False and Application.ScreenUpdating = True

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