VBA Excel代码不删除“空白”单元格

时间:2016-02-21 04:53:20

标签: excel vba excel-vba

我一直在使用此代码来定义包含数据的范围的变量。然后,我尝试使用它来清除工作表(减去标题)但是它会一直显示最后一行是A2,例如,当W4中的先前粘贴中存在“ghost”数据时。

为什么这段代码找不到真正的最后一行?即使我运行了这个,然后去Find Special>最后一行 - 它找到最后粘贴的空白范围(“空”)。您可以看到变量LastRow始终为“1”。与此同时,我刚刚将删除范围设置为A2:W5000,因为我知道我永远不会有那么多数据,但让VBA为我找到真正的最后一行并存储在变量中会很好。 谢谢,

Public Sub ClearSheet()
Dim LastRow As Long
Dim LastCol As Long
If WorksheetFunction.CountA(Cells) > 0 Then
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows,         SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns,     SearchDirection:=xlPrevious).Column
        MsgBox (LastRow)
        MsgBox (LastCol)
Range("A2").Resize(LastRow, LastCol).EntireRow.Delete 'retains headers in A1:W1

1 个答案:

答案 0 :(得分:0)

尝试UsedRange功能。 UsedRange包含“ghost”单元格,您可以对其进行操作以删除不需要的行,不包括标题,如下所示:

Sub RemoveUnwantedRows()

    Dim wk As Worksheet
    Set wk = ActiveSheet

    Dim rng As Range

    Set rng = wk.UsedRange
    'Error handling incase there are no "Ghost Cells".
    On Error Resume Next
    Set rng = rng.Resize(rng.Rows.Count - 1, rng.Columns.Count)
    Set rng = rng.Offset(1, 0)
    rng.Rows.Delete
    On Error GoTo 0
    'Proof that only the headers are left, you can leave this code out if you want.
    wk.UsedRange.Select

End Sub