删除“H:H”具有正值的行

时间:2016-03-22 17:55:30

标签: excel vba excel-vba

我需要在排序后删除H列中正值开始的行。我试图使用查找功能。我知道> 0不起作用,但不知道从哪里开始。如果我能弄清楚如何选择向上和删除,我可以将排序切换为降序并搜索“ - ”。

    Source_Workbook.Worksheets("Sheet1").Activate
Source_Workbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("H:H"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
Cells.Select

With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A1:R65800")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With


Columns("H:H").Select
Selection.Find(What:=">0", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Select

Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.EntireRow.Delete

2 个答案:

答案 0 :(得分:1)

试试这个,循环遍历范围内的每个单元格。仔细检查我的lastRow是否是准确且可持续的方式来获取项目的最后一行:

Sub t()
Dim lastRow as Long, i as Long
Dim myWS as worksheet
Dim mySourceWB as workbook
Dim cel as Range

Set mySourceWB = Source_Workbook ‘ you will probably need to tweak this
Set myWS = mySourceWB.Worksheets(“Sheet1”)

myWS.Sort.SortFields.Add Key:=myWS.Range("H:H"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

With myWS.Sort
    .SetRange Range("A1:R65800")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With ‘myWS.sort

With myWS
    lastRow = .Cells(.Rows.Count,8).End(xlup).Row
    For i = lastRow to 1 ‘ change to 2, if you have headers
    If .cells(i,8).Value > 0 Then
        .Rows(i).EntireRow.Delete
    End if
    Next i
End with ‘myWS
End Sub

答案 1 :(得分:1)

这似乎适合单个字段Range.AutoFilter Method

Sub del_positives()
    With ActiveWorkbook.Worksheets("Sheet1")
        'turn off any exiting autofilter
        If .AutoFilterMode Then .AutoFilterMode = False
        'work with the block of cells radiating out from A1
        With .Cells(1, 1).CurrentRegion
            'apply the positive number filter to column H
            .AutoFilter field:=8, Criteria1:=">0"
            'step off the header row
            With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                'determine if there are cells to delete
                If CBool(Application.Subtotal(102, .Cells)) Then
                    'if there are, delete them
                    .SpecialCells(xlCellTypeVisible).EntireRow.Delete
                End If
            End With
            'remove the filter
            .AutoFilter
            'if you still want to sort, then do so
            .Cells.Sort Key1:=.Columns(8), Order1:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub

如果您想继续排序输出,我已添加了Range.Sort method