如何使Selection.AutoFilter从第3行而不是第1行开始

时间:2013-05-28 23:44:35

标签: excel excel-vba autofilter vba

我有这段代码:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
    Application.ScreenUpdating = False
    If Target.Value <> "" Then
            Set wbks = Workbooks.Open("\\MyPath\Workbook.xlsx")
        wbks.Sheets("Control").Activate
        ActiveSheet.Range("A1").Select
        Selection.AutoFilter
        Selection.AutoFilter Field:=7, Criteria1:=Target.Value '7 is the filter # column
    End If
End Sub

仅当工作表control中的标题位于第1行时,它才能正常工作 我的问题是\\MyPath\Workbook.xlsx只读文件,其标题从第3行开始。

2 个答案:

答案 0 :(得分:4)

尝试以下代码:

  • 避免在代码中使用Select。
  • 在程序开始时关闭屏幕更新时,始终将Application.ScreenUpdating = True设置在底部。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    If Target.Value <> "" Then
        Set wbks = Workbooks.Open("\\MyPath\Workbook.xlsx")
        wbks.Sheets("Control").Activate
        wbks.Sheets("Control").Range("A3:G3").AutoFilter Field:=7, Criteria1:=Target.Value    '7 is the filter # column
    End If

    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

答案 1 :(得分:1)

尝试在自动过滤器之前添加此代码

Rows("3:3").Select

制作代码:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
    Application.ScreenUpdating = False
    If Target.Value <> "" Then
            Set wbks = Workbooks.Open("\\MyPath\Workbook.xlsx")
        wbks.Sheets("Control").Activate
        ActiveSheet.Range("A1").Select
        Rows("3:3").Select
        Selection.AutoFilter
        Selection.AutoFilter Field:=7, Criteria1:=Target.Value '7 is the filter # column
    End If
End Sub

希望它有所帮助, 布鲁诺