1. 程式人生 > >【VBA研究】工作表自己主動篩選模式檢測

【VBA研究】工作表自己主動篩選模式檢測

模式 處理 name ins work sdn edr rda all

作者:iamlaosong

用VBA程序處理Excel數據文件。用戶的數據文件有時處於自己主動篩選模式,往往導致數據處理不對。為此,須要檢測工作表是否處於該模式,假設是,則去掉自己主動篩選。語句例如以下:

If ActiveSheet.AutoFilterMode = True Then Selection.AutoFilter

這個語句一般僅僅用於去掉自己主動篩選,盡管Selection.AutoFilter也能夠加上自己主動篩選,但篩選位置卻可能在當前單元格處,所以要註意。加自己主動篩選前,現將單元格定位到字段標題處。然後用例如以下

語句:

If ActiveSheet.AutoFilterMode = False Then Selection.AutoFilter


假設檢測其他非活躍的工作表,能夠用以下語句:

If Worksheets("sheet1").AutoFilterMode = True Then

Worksheets("sheet1").Range("A1").AutoFilter


附: Range.AutoFilter Method
Excel Developer Reference
Filters a list using the AutoFilter.

Syntax

expression.AutoFilter(Field, Criteria1, Operator, Criteria2, VisibleDropDown)

expression An expression that returns a Range object.

Parameters

Name Required/Optional Data Type Description
Field Optional Variant The integer offset of the field on which you want to base the filter (from the left of the list; the leftmost field is field one).
Criteria1 Optional Variant The criteria (a string; for example, "101"). Use "=" to find blank fields, or use "<>" to find nonblank fields. If this argument is omitted, the criteria is All. If Operator is xlTop10Items, Criteria1 specifies the number of items (for example, "10").
Operator Optional XlAutoFilterOperator One of the constants of XlAutoFilterOperator specifying the type of filter.
Criteria2 Optional Variant The second criteria (a string). Used with Criteria1 and Operator to construct compound criteria.
VisibleDropDown Optional Variant True to display the AutoFilter drop-down arrow for the filtered field. False to hide the AutoFilter drop-down arrow for the filtered field. True by default.

Return Value
Variant

Remarks

If you omit all the arguments, this method simply toggles the display of the AutoFilter drop-down arrows in the specified range.

Example

This example filters a list starting in cell A1 on Sheet1 to display only the entries in which field one is equal to the string "Otis". The drop-down arrow for field one will be hidden.

Visual Basic for Applications
Worksheets("Sheet1").Range("A1").AutoFilter _
    field:=1, _
    Criteria1:="Otis", _
    VisibleDropDown:=False



【VBA研究】工作表自己主動篩選模式檢測