自动过滤到最后一排纸张

时间:2015-07-13 00:37:17

标签: excel vba excel-vba

我有一个包含30,000多行的工作簿来过滤。我需要过滤F列中以314开头的值。我有以下代码可以过滤到特定范围。结果表单将每月更改一次。所以在代码中应该没有明确的最后一行,我需要找到工作表的最后一行(最后一行每个月都会更改)。我尝试调整代码,但它不起作用。这是我调整的代码:

Sub Del314()
Dim ws As Worksheet
Dim LR As Long
Set ws = Sheets("Source")
LR = ws.Cells(Rows.Count, "A").End(xlUp).Row

ws.Range("A1:AF" & LR).AutoFilter Field:=6, Criteria1:="=314*", Operator:=xlAnd

ws.Range("A2:AF" & LR).SpecialCells(xlCellTypeVisible).ClearContents
ws.AutoFilterMode = False

End Sub

虽然这是原始代码(其中它仅针对特定范围,直到行30436):

Sub Del314()
Dim ws As Worksheet
Set ws = Sheets("sheet1")

ws.Range("$A$1:$AF$30436").AutoFilter Field:=6, Criteria1:="=314*" _
, Operator:=xlAnd

Dim LR As Long
LR = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("A2:AF" & LR).SpecialCells(xlCellTypeVisible).ClearContents
ws.AutoFilterMode = False
End Sub'

任何建议将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

Public Sub Del314()

    Dim ws As Worksheet
    Dim lr As Long

    Set ws = Worksheets("Source")
    lr = ws.Cells(Rows.Count, "a").End(xlUp).Row

    ws.Range("a1:af1").Resize(lr).AutoFilter Field:=6, Criteria1:="=314*", Operator:=xlAnd

    ws.Range("a2:af2").Resize(lr - 1).SpecialCells(xlCellTypeVisible).ClearContents
    ws.AutoFilterMode = False

End Sub

编辑:

尝试使用对象变量...

Public Sub Del314()

    Dim ws As Worksheet
    Dim lr As Long
    Dim r As Range

    Set ws = Worksheets("Source")
    lr = ws.Cells(Rows.Count, "a").End(xlUp).row
    Set r = ws.Range("a1:af1").Resize(lr)

    r.AutoFilter Field:=6, Criteria1:="=314*", Operator:=xlAnd

    r.Offset(1).SpecialCells(xlCellTypeVisible).ClearContents
    ws.AutoFilterMode = False

End Sub

编辑#2:

虽然我讨厌这样做,但我们先尝试选择范围......

Public Sub Del314()

    Dim ws As Worksheet
    Dim lr As Long
    Dim r As Range

    Set ws = Worksheets("Source")
    lr = ws.Cells(Rows.Count, "a").End(xlUp).Row
    Set r = ws.Range("a1:af1").Resize(lr)
    r.Select

    ws.AutoFilterMode = False
    Selection.AutoFilter Field:=6, Criteria1:="=314*", Operator:=xlAnd

    r.Offset(1).SpecialCells(xlCellTypeVisible).ClearContents
    ws.AutoFilterMode = False

End Sub

编辑#3:

行。还有一个变种......

Public Sub Del314()

    Dim ws As Worksheet
    Dim lr As Long
    Dim r As Range

    Set ws = Worksheets("Source")
    lr = ws.Cells(Rows.Count, "a").End(xlUp).Row
    Set r = ws.Range("a1:af1").Resize(lr)

    ws.AutoFilterMode = False
    r.AutoFilter Field:=6, Criteria1:="=314*", Operator:=xlAnd

    r.Offset(1).SpecialCells(xlCellTypeVisible).ClearContents
    ws.AutoFilterMode = False

End Sub