Excel宏删除排序的行

时间:2019-02-12 23:41:23

标签: excel vba

在编写要对数据进行小计的宏,将数据复制到另一个工作表,然后过滤列和删除那些行时遇到了问题。问题在于,每次运行宏时,我需要删除的数据范围都会变化。 这是我目前拥有的示例:

Range("A2").Select
    Columns("A:C").Select
    Selection.Subtotal GroupBy:=1, Function:=xlCount, TotalList:=Array(3), _
        Replace:=True, PageBreaks:=False, SummaryBelowData:=True
        Range("A2:C2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
        Range("A2").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Range("$A$1:$C$396").AutoFilter Field:=2, Criteria1:="<>"
    Rows("2:394").Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
    ActiveSheet.Range("$A$1:$C$42").AutoFilter Field:=2
    Range("A22").Select
    Selection.End(xlDown).Select
    Rows("42:42").Select
    Selection.Delete Shift:=xlUp

Any help would be greatly appreciated. 

1 个答案:

答案 0 :(得分:0)

所以,代替这个:

"$A$1:$C$396"
"$A$1:$C$42"

动态查找最后使用的行和最后使用的列。

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ActiveSheet

'Ctrl + Shift + End
  LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

然后。 。

Dim sht As Worksheet
Dim LastColumn As Long

Set sht = ThisWorkbook.Worksheets("Sheet1")

'Using UsedRange
  sht.UsedRange 'Refresh UsedRange
  LastColumn = sht.UsedRange.Columns(sht.UsedRange.Columns.Count).Column

您需要更多帮助吗,还是可以从这里找出答案?