使用Filter选项将值从一个工作表复制到另一个工作表

时间:2014-01-20 07:19:01

标签: excel vba excel-vba

我正在尝试使用“过滤器”选项将值从一个Excel工作表复制到另一个工作表。例如,我只使用了10条记录,但实时我不确定将出现的数据。此外,我需要知道过滤器后的第一个单元格值。例如,如果我使用过滤器,则第一个值反映为B4,下次显示B6。我还需要使用宏动态选择它。

ActiveSheet.Range("$A$1:$BG$10").AutoFilter Field:=2, Criteria1:="2"
Range("B5:BG5").Select

应修改上述代码。而不是$ BG $ 10应该是行数,而不是B5:BG5它必须是过滤后的第一个单元格。

2 个答案:

答案 0 :(得分:0)

请尝试以下代码:

Sub test()
    Dim lastRow As Long, firstVisibleRow As Long

    ActiveSheet.AutoFilterMode = False
    'find last non empty row number in column A'
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    'apply filter'
    Range("$A$1:$BG$" & lastRow).AutoFilter Field:=2, Criteria1:="2"

    On Error GoTo errHandler
    'find first visible row number in the filtered range, if there is no rows matching the filter criteria, we'll get message from the MsgBox'
    firstVisibleRow = Range("$A$2:$BG$" & lastRow).SpecialCells(xlCellTypeVisible).Row
    On Error GoTo 0
    'select range'
    Range("B" & firstVisibleRow & ":BG" & firstVisibleRow).Select

    Exit Sub
errHandler:
        MsgBox "There is no rows matching the filter criteria"
End Sub

答案 1 :(得分:0)

试试这个:

Dim rngToFilter As Range

With ActiveSheet
     .AutoFilterMode = False 'to make sure no filter is applied yet
     Set rngToFilter = .Range("A1", .Range("BG" & Rows.Count).End(xlUp)) 'set the dynamic range
     rngToFilter.AutoFilter Field:=2, Criteria1:="2" 'apply the filter
     rngToFilter.Resize(.Range("BG" & Rows.Count).End(xlUp).Row - 1).Offset(1, 0).SpecialCells(xlCellTypeVisible).Select 'Offset 1 row to exclude the header, resize to select the first row only.
End With

以上代码选择所有已过滤的项目 我想要你这样只选择过滤的第一项,然后在下面使用。

Sub Sample()

Dim rngToFilter As Range, rngFilter As Range
Dim i As Integer

With ActiveSheet
    .AutoFilterMode = False 'to make sure no filter is applied yet
    Set rngToFilter = .Range("A1", .Range("BG" & Rows.Count).End(xlUp)) 'set the dynamic range
    rngToFilter.AutoFilter Field:=2, Criteria1:="2" 'apply the filter
    Set rngFilter = rngToFilter.Resize(.Range("BG" & Rows.Count).End(xlUp).Row - 1).Offset(1, _
                        0).SpecialCells(xlCellTypeVisible)
    rngToFilter.Resize(.Range("BG" & Rows.Count).End(xlUp).Row - _
                    (rngFilter.Cells.Count / rngFilter.Columns.Count)).Offset(1, _
                        0).SpecialCells(xlCellTypeVisible).Select
End With

End Sub

还没有错误处理程序。
我留给你。 :d