满足条件时重置循环Excel VBA

时间:2018-10-17 01:27:03

标签: excel vba

我有一张Excel工作表。我想在满足条件时重置循环,因为我有两个条件。但是,我想到了从该解决方案网站Reset a for loop when a condition is met vba的for循环旁边执行步骤。它没有作用,因为它仅适用于数字而不是A1。解决此问题的解决方案是什么?谢谢。

Sub run()
 Set MR = Range("A1:Q1")
    'Loop through the cell in the first row
    For Each cell In MR
        If cell.Value = "First Discovered" Or cell.Value = "Last Observed" Then cell.EntireColumn.Delete
    Next cell
End Sub

1 个答案:

答案 0 :(得分:1)

如果您想查看第一行的A:Q列,则不需要。关键是要避免在循环内删除,因为这会在循环范围内产生偏移。

以下解决方案将遍历您的范围并将目标单元格添加到Union(单元格集合)中,一旦循环完成,它将删除Union中所有单元格的列< / p>


也是

添加Option Explicit。您需要声明变量,Option Explicit将迫使您这样做。这也间接充当便捷的拼写检查器。

最后一件事:我将变量'cell'更改为'myCell',以避免与已经存在的对象Cells混淆


Option Explicit

Sub run()

Dim MR As Range, myCell As Range, DeleteMe As Range

Set MR = Range("A1:Q1")

For Each myCell In MR
    If myCell = "First Discovered" Or myCell = "Last Observed" Then
        If DeleteMe Is Nothing Then
            Set DeleteMe = myCell
        Else
            Set DeleteMe = Union(DeleteMe, myCell)
        End If
    End If
Next myCell

If Not DeleteMe Is Nothing Then DeleteMe.EntireColumn.Delete

End Sub