根据单元格值

时间:2016-10-25 09:02:47

标签: excel-vba vba excel

该代码旨在删除数据的列标题(在导入多个文件之后)。但是我收到错误:“1004”这是“应用程序定义的或对象定义的错误”。我在SO上引用了不同的解决方案,但无济于事。

在我运行此代码snippit之前,我删除了空行,并将其包含在内,以显示哪些功能正常,甚至可以保存密钥。

'Remove all rows with blanks first
Set wb = Workbooks(ThisWorkbook.Name)
'Remove blank rows based on if column 'B' is blank as a and B are filled when there is risk key showing
wb.Worksheets("BatchData").Activate
Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
'Now to delete based on column headers!
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
'Filter Column A and delete selection
'############# Error line below
ActiveSheet.Range("A1:" & A & ":" & LastRow).AutoFilter Field:=2, Criteria1:= _
        "=Item", Operator:=xlOr, Criteria2:="="
Selection.EntireRow.Delete

编辑:

修改后的代码,根据评论进行了一些调整,并且我引用了字段“2”,并试图使用“A”,即1。

Dim LastRow As Long
LastRow = wb.Worksheets("BatchData").Cells(Rows.Count, 1).End(xlUp).Row
'Filter Column A and delete selection
ActiveSheet.Range("A1:A" & LastRow).AutoFilter Field:=1, Criteria1:= _
        "=Item", Operator:=xlOr, Criteria2:="="

ActiveSheet.Range(“$ A $ 1:$ A $”& LastRow).Offset(0,0).SpecialCells _     (xlCellTypeVisible).EntireRow.Delete

基于的最后一行编辑; VBA: How to delete filtered rows in Excel?但偏移量从1,0变为0

1 个答案:

答案 0 :(得分:1)

尝试稍微清理一下代码,并消除可能的错误,请尝试下面的代码,它会过滤A列中的“Item”,然后您可以使用以下两个选项之一:

选项1:删除所有行,包括标题行。

选项2:删除除标题行之外的所有行。

Option Explicit

Sub DeleteFilteredRows()

Dim LastRow As Long

With ThisWorkbook.Worksheets("BatchData")

    ' remove blank rows based on if column 'B' is blank as a and B are filled when there is risk key
    .Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

    ' find last row in Column !
    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row

    ' Filter Column A 
    .Range("A1:A" & LastRow).AutoFilter Field:=1, Criteria1:= _
            "=Item", Operator:=xlOr, Criteria2:="="

    ' option 1: delete also header row
    .Range("A1:A" & LastRow).SpecialCells _
        (xlCellTypeVisible).EntireRow.Delete

    ' option 2: if you want to keep the header row
    .Range("A1:A" & LastRow).Offset(1, 0).SpecialCells _
        (xlCellTypeVisible).EntireRow.Delete

End With

End Sub