简体   繁体   English

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

[英]VBA Excel code not deleting “blank” cells

I have been using this code to define a variable of a range that contains data. 我一直在使用此代码来定义包含数据的范围的变量。 I then tried to use it to clear a worksheet (minus the headers) but it keeps showing that the last row is A2, when there is "ghost" data leftover from a previous paste in range W4 for example. 然后,我尝试使用它来清除工作表(减去标题),但是当例如W4范围中的上一个粘贴有剩余的“重影”数据时,它一直显示最后一行是A2。

Why isn't this code finding the true last row? 为什么这段代码没有找到真正的最后一行? Even after I run this, then go to Find Special > Last Row - it finds the last pasted blank range (which is "empty"). 即使在运行此命令后,也要转到“查找特殊字符”>“最后一行”-它会找到最后粘贴的空白范围(“空”)。 You can see the variable LastRow is always "1". 您可以看到变量LastRow始终为“ 1”。 In the mean time, I've just been setting the delete range to A2:W5000 because I know I'll never have that much data, but it would be nice to have VBA find the true last row for me and store in a variable. 同时,我刚刚将删除范围设置为A2:W5000,因为我知道我永远不会有那么多数据,但是最好让VBA为我找到真正的最后一行并存储在变量中。 Thank you, 谢谢,

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

Try the UsedRange function. 尝试使用UsedRange函数。 UsedRange includes "ghost" cells, and you can manipulate it to delete unwanted rows, excluding the header, like so: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM