首页 > 解决方案 > ="" 不会删除附加了公式的行。Excel

问题描述

如果 A 中没有值,我想删除一行。如果 A86 没有值并且没有“3060”,它将删除。虽然第 88 行之类的东西在 A 中没有价值,但它不会删除。单元格 D88 有一个公式 ='劳动力预算突破'!D97,它不会删除。我希望删除这些单元格 D:F,因为它们的值为 A=""。

Sub DeleteRowIfCostCode()

Dim count, i As Long

count = Sheet1.Cells(Rows.count, "A").End(xlUp).Row

'msgbox count

i = 6
Do While i <= count

If (Cells(i, 1)) = "" Then

Rows(i).EntireRow.Delete
i = i - 1
End If

i = i + 1
count = Sheet1.Cells(Rows.count, "A").End(xlUp).Row

Loop

End Sub

显示工作表

标签: excelvba

解决方案


阅读了您的代码并查看了您的屏幕截图,我想我发现了您最大的问题。

就是这一行:

count = Sheet1.Cells(Rows.count, "A").End(xlUp).Row

您会看到,根据您的屏幕截图,count将设置为86 因此,您的代码将从第 6 行循环到第 86 行,然后停止。这就是为什么它不会删除第 87 行到第 100 行中的空白记录的原因。您(不小心?)告诉它不要这样做。

现在,我不知道您的工作表的前 5 行是什么,但我将假设您在第 5 行中有一个表头行。因此,如果您想计算其中有多少行总的来说,你会更好地使用这样的东西:

count = Sheet1.Cells(5, 1).CurrentRegion.Rows.Count + 4 'There are 4 rows before the header

这将使用Range.CurrentRegion属性自动检测 D、E 和 F 列中仍有数据,即使A 列中没有任何数据。(虽然这是计算行数的更好方法,但有更好的方法删除空白行的方法——因此,我们实际上不会使用那行代码。否则,我们将进入XY 问题领域;最好修复我们的方法)

现在,正如 Scott Craner 在评论中指出的那样,最好让您的代码在删除行时运行反向循环。我们可以用Do While7 行IfFor语句(或 5 行,如果您IfFor循环内使用内联)替换您的整个语句:

If count >= 6 Then 'prevent infinite loop
    For i=count to 6 step -1
        If Sheet1.Cells(i, 1).Value = "" Then
            Sheet1.Rows(i).Delete
        End If
    Next i
End If

至于确保在结束后删除任何空白行的最佳方法?只需删除工作表底部的所有内容!完整代码如下:

Sub DeleteRowIfCostCode()
    Dim count As Long, i As Long 'Declare the Type for both variables

    'Safety check, in case there aren't any rows with data. Always at least 6
    count = WorksheetFunction.Max(Sheet1.Cells(Sheet1.Rows.count, 1).End(xlUp).Row, 6)

    'msgbox count 'debug code?

    'Delete any rows after the last row with a value in column A
    Sheet1.Range(Sheet1.Cells(count+1,1), Sheet1.Cells(Sheet1.Rows.Count,1)).EntireRow.Delete

    'Find any blank rows in the middle of the data, working backwards from the end
    For i=count to 6 step -1
        If Sheet1.Cells(i, 1).Value = "" Then
            Sheet1.Rows(i).Delete
        End If
    Next i

End Sub

推荐阅读