过滤值并删除可见行

时间:2018-01-17 19:19:47

标签: excel vba excel-vba

我有一些代码不能像我想的那样工作。它应该在列AL上过滤“1”,然后删除所有可见的行,然后显示所有行。我的数据从P列开始,我认为AL列距离P是23列,所以我把23列用于该字段。我在前3行中有标题,所以我将其设置为偏移3行。

当我运行它时,它说

  

对象'_Worksheet'的方法'范围'失败

我是VBA的初学者,所以我还在学习,但我不确定这是导致错误的部分原因。我尝试了一切我能想到的能力。据我所知......它应该基于谷歌搜索其他类似的代码。

这是有问题的代码部分:

Sub copypaste()

Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
Dim endrow As Long


Set wsI = ThisWorkbook.Sheets("Sheet2")

Set wsO = ThisWorkbook.Sheets("Sheet1")

Application.ScreenUpdating = False


With wsO

wsO.Range("AL" & Lines).AutoFilter Field = 22, Criteria1:="1"
wsO.Range("AL" & Lines).Offset(3, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
wsO.ShowAllData

End With

1 个答案:

答案 0 :(得分:1)

你的问题是:

  

wsO.Range("AL" & Lines)

您尚未向Lines声明或分配值。

此外,您还需要包含整个表格范围,而不仅仅是一列:

wsO.Range("P2:AL" & Lines)

所以:

Sub copypaste()

Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
Dim endrow As Long
Dim Lines As Long

Set wsI = ThisWorkbook.Sheets("Sheet2")
Set wsO = ThisWorkbook.Sheets("Sheet1")

Application.ScreenUpdating = False


With wsO
    Lines = .Cells(.Rows.Count, "P").End(xlUp).Row
    .Range("P13:AL" & Lines).AutoFilter field:=23, Criteria1:="1"
    On Error Resume Next
        .Range("P14:AL" & Lines).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    On Error Goto 0
    .ShowAllData
End With