【问题标题】:Iterate through cells in a range遍历范围内的单元格
【发布时间】:2011-02-28 17:26:55
【问题描述】:

目前,我正在使用以下代码检查某个单元格区域中的 A 列是否有 #N/A 值,如果找到,我将删除该行。

With Sheets(Sheet)
        For LRow = 45 To 29 Step -1
            With .Cells(LRow, "A")
                If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete
            End With
        Next LRow
    End With

我需要扩展它,所以我检查了所有列 1 到 10,而不仅仅是 A。我尝试了这个轻微的修改(嵌套另一个循环),但它不起作用。有什么建议吗?

With Sheets(Sheet)
        For LRow = 45 To 29 Step -1
            For LCol = 10 To 1 Step -1
                With .Cells(LRow, LCol)
                    If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete
                End With
            Next LCol
        Next LRow
    End With

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这里有两个问题:

    • 嵌套
    • 在任何给定行上,一旦发现 N/A,您需要中止循环

    试试

    Set sh = Sheets(Sheet)
    For LRow = 45 To 29 Step -1
        For LCol = 10 To 1 Step -1
            If (CVErr(sh.Cells(LRow, LCol).Value) = CVErr(xlErrNA)) Then 
                sh.Cells(LRow, 1).EntireRow.Delete
                Exit For ' Exit the LCol loop
            End If
        Next LCol
    Next LRow
    

    【讨论】:

      【解决方案2】:

      这可能会在英语以外的其他语言中失败

      Sub DeleteNA()
      
          Dim rRange As Range
          Dim rFound As Range
      
          Const sNA As String = "#N/A"
      
          Do
              Set rRange = Sheet1.Range("A29:F49")
              Set rFound = rRange.Find(sNA, , xlValues, xlWhole, xlByRows)
              If Not rFound Is Nothing Then
                  rFound.EntireRow.Delete
              Else
                  Exit Do
              End If
          Loop
      
      End Sub
      

      更改 A29:F49 以适合您的数据。

      【讨论】:

        【解决方案3】:

        你可以采取稍微不同的方法

        Sheets("Sheet1").Select
        Set cols = Range("A1:D80")
        For Each Cell In cols
            If Cell.Value = "XXX" Then
                Cell.EntireRow.Delete
            End If
        Next
        

        【讨论】:

        • 我得到一个“对象不支持设置选择行的属性或方法
        • 您需要先选择工作表 - 我已将其添加到
        • 好吧,“选择”是一个错误的变量名选择。相应地编辑了答案。 VBA 自动将“selection”更改为“Selection”,这是一个保留关键字...
        【解决方案4】:

        我认为您使用的嵌套 'with' 子句存在问题。

        您可以定义一个适当的范围并使用“for each”循环,这将使事情更清晰、更易于阅读。出于测试目的,我将一个范围命名为“MyRange”。

        Sub test()
        
            Dim cell As Excel.Range
        
            For Each cell In [myRange]
        
                If CVErr(cell.Value) = CVErr(xlErrNA) Then cell.EntireRow.Delete
        
            Next cell
        
        End Sub
        

        【讨论】:

          猜你喜欢
          • 2018-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-18
          • 1970-01-01
          • 2016-04-20
          • 2014-09-25
          • 2019-06-05
          相关资源
          最近更新 更多