【问题标题】:How to delete column from range if cell contains specific value in VBA/Excel如果单元格包含 VBA/Excel 中的特定值,如何从范围中删除列
【发布时间】:2014-01-29 02:10:03
【问题描述】:

我正在尝试编写一些 VBA 来检查一系列列(行 M 到 GD)中单元格的值,如果单元格不包含“YY”,请删除该列。

要检查的单元格总是在第 22 行

我尝试了以下方法,但速度非常慢。

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

是否有人对如何加快速度或解决此问题的更好方法有任何建议?

谢谢

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    是否有人对如何加快速度或解决此问题的更好方法有任何建议?

    是的。 不要删除循环中的列。使用Union 方法。这是一个例子。我已经对代码进行了注释,因此您理解它不会有问题。不过,如果您这样做,则只需回帖即可。

    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
    

    这将在眨眼之间执行,但如果您愿意,您可以将代码夹在 Application.ScreenUpdating = FalseApplication.ScreenUpdating = True 之间

    【讨论】:

    • +1,这很好,我删除行时必须使用它。
    • @enderland:过去在 SO 中已经介绍了使用该方法删除行 :) Link1Link2 以及更多如果您搜索 SO
    • @SiddharthRout 在删除行时,我更多的是提醒自己使用Union :) 通常我删除的内容不够重要,但是,它肯定会避免那种烦人的“确保您正确地向后迭代行”问题。
    • 它就像一个魅力,非常感谢您的帮助。我打算自己了解一下 Unions,直到现在才使用它们。
    猜你喜欢
    • 1970-01-01
    • 2017-06-20
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多