首页 > 解决方案 > 满足条件时重置循环excel vba

问题描述

我有一张excel表格。我想在满足条件时重置循环,因为我有两个条件。但是,我想在这个解决方案网站的 for 循环旁边实施步骤,当满足条件时重置一个 for 循环 vba。它不起作用,因为它仅适用于数字而不是 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

标签: excelvba

解决方案


如果要查看第一行的列,则无需重置循环。A:Q关键是避免在循环内删除,因为这会在循环范围内产生变化。

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


还,

添加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

推荐阅读