【问题标题】:Delete rows based on cell value not working根据单元格值删除行不起作用
【发布时间】:2019-01-16 14:03:42
【问题描述】:

我在名为 New 的工作表中有一些数据,我的数据在 A 列到 K 列中。但是,出于数据分析的目的,E 到 H 列故意留空,并且我没有标题,因此我的数据从单元格 A1 开始。现在在 A 列中,我们在单元格中有颜色,我想删除所有不是白色的行,所以保留其中没有颜色的行。

我做了一些研究,但我在网上找到的所有代码要么删除了整张工作表,要么只是通过代码而没有任何反应。以下是我目前正在使用的那些没有任何作用的。我用F8还是没有报错。

查看我的示例数据的图像,我正在尝试使用没有任何颜色的单元格获得结果。我试图删除颜色索引的引号,但它仍然不起作用。

 Sub deleterow()

 lastRow = Worksheets("New").Cells(Rows.Count, "A").End(xlUp).Row
 For i = lastRow To 1 Step -1
      If Worksheets("New").Cells(i, 1).Interior.ColorIndex <> "2" Then
           Rows(i).EntireRow.Delete
           i = i + 1
      End If
 Next I

 End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试下面的代码:

    Option Explicit
    
    Sub deleterow()
    
    Dim i As Long, LastRow As Long
    
    With Worksheets("New")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    
        For i = LastRow To 1 Step -1
            'If .Cells(i, 1).Interior.Color <> xlNone Then
            ' replace RGB(255, 255, 255) with the "white" color
            If .Cells(i, 1).Interior.Color <> RGB(255, 255, 255) Then
                .Rows(i).Delete
            End If
        Next i
    End With
    
    End Sub
    

    【讨论】:

    • 感谢您的回复,但您的代码会删除整个工作表。
    • @sc1324 你在 A 列的颜色是白色吗?还是空的?
    • 除了 E 列到 H 列之外的任何列中都没有空白单元格。在 A 列中,有些单元格有颜色,有些没有,所以如果有单元格颜色,我会尝试删除行A 列。
    • @sc1324 作为值和颜色不为空。尝试编辑的代码。
    • 我的意思是 A 列中的空白单元格表示我们是否到达数据范围的末尾,这就是我们定义 lastrow 的原因。
    【解决方案2】:

    删除无颜色行

    联合版

    Option Explicit
    
    Sub DeleteNoColorRow()
    
        Const cSheet As Variant = "Sheet1"  ' Worksheet Name/Index
        Const cFirstR As Integer = 1        ' First Row
        Const cColumn As Variant = "A"      ' Column Letter/Number
    
        Dim rngU As Range     ' Union Range
        Dim lastRow As Long   ' Last Row
        Dim i As Long         ' Row Counter
    
        With ThisWorkbook.Worksheets(cSheet)
            lastRow = .Cells(.Rows.Count, cColumn).End(xlUp).Row
            For i = cFirstR To lastRow
                If .Cells(i, cColumn).Interior.ColorIndex <> xlNone Then
                    If Not rngU Is Nothing Then
                        Set rngU = Union(rngU, .Cells(i, cColumn))
                      Else
                        Set rngU = .Cells(i, cColumn)
                    End If
                End If
            Next
        End With
    
        If Not rngU Is Nothing Then
            rngU.EntireRow.Delete ' Hidden = True
            Set rngU = Nothing
        End If
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2018-11-11
      • 2017-11-20
      相关资源
      最近更新 更多