AutoFilterつながりで。
フィルタをかけている時、設定している抽出条件を取得したいというQがたまにあります。
ヘルプの[AutoFilter オブジェクト]関連に使用例が載ってるのですが
状況によってはエラーだし、[Filters プロパティの使用例]は意味不明なところがあるからわかりにくいのでしょうか。
#ぃや、意味不明なのはこれに限った事ではないので今さら..ですが :-/
...ついでに。
2007からは変わったようですが、2003以前のバージョンでは
抽出条件を設定しているFilterのDropDown▼の『青』が区別しにくいので変更できないか、というQも時々見かけます。
下記は、条件設定した時のイベントをSUBTOTAL関数を使って擬似的に捉え、
[On プロパティ]で判断してセルに色付けするサンプルです。
AutoFilter監視対象シートがSheet1だとします。
それとは別のダミーシートの任意の1セルに数式を設定します。
=SUBTOTAL(3,Sheet1!A:A)
あとは、そのダミーシートのシートモジュールのCalculateイベントを使います。
工夫すれば、アドイン化してApplication単位での汎用処理が可能ですが、
そこまで苦労するほどのニーズがあるのかどうか。
フィルタをかけている時、設定している抽出条件を取得したいというQがたまにあります。
ヘルプの[AutoFilter オブジェクト]関連に使用例が載ってるのですが
状況によってはエラーだし、[Filters プロパティの使用例]は意味不明なところがあるからわかりにくいのでしょうか。
#ぃや、意味不明なのはこれに限った事ではないので今さら..ですが :-/
Sub try() Dim n As Long Dim i As Long With ActiveSheet If .AutoFilterMode Then n = .AutoFilter.Filters.Count ReDim v(1 To n) For i = 1 To n With .AutoFilter.Filters(i) v(i) = i & vbTab & .On If .On Then v(i) = v(i) & vbTab & .Operator & vbTab & .Criteria1 If (.Operator = xlAnd) Or (.Operator = xlOr) Then v(i) = v(i) & vbTab & .Criteria2 End If End If End With Next End If End With 'Debug.Print Join(v, vbLf) MsgBox Join(v, vbLf) End Sub
...ついでに。
2007からは変わったようですが、2003以前のバージョンでは
抽出条件を設定しているFilterのDropDown▼の『青』が区別しにくいので変更できないか、というQも時々見かけます。
下記は、条件設定した時のイベントをSUBTOTAL関数を使って擬似的に捉え、
[On プロパティ]で判断してセルに色付けするサンプルです。
AutoFilter監視対象シートがSheet1だとします。
それとは別のダミーシートの任意の1セルに数式を設定します。
=SUBTOTAL(3,Sheet1!A:A)
あとは、そのダミーシートのシートモジュールのCalculateイベントを使います。
'SheetModule Option Explicit Private Sub Worksheet_Calculate() Static r As Range Dim f As Filter Dim i As Long On Error GoTo errHndler With Sheets("sheet1") If .AutoFilterMode Then With .AutoFilter If r Is Nothing Then Set r = .Range.Rows(1) For Each f In .Filters i = i + 1 '33が、識別用 ColorIndex。任意で。 r.Cells(i).Interior.ColorIndex = IIf(f.On, 33, xlNone) Next f End With Else If Not r Is Nothing Then r.Interior.ColorIndex = xlNone Set r = Nothing End If End With errHndler: If Err.Number <> 0 Then MsgBox Err.Number & ":" & Err.Description End Sub
工夫すれば、アドイン化してApplication単位での汎用処理が可能ですが、
そこまで苦労するほどのニーズがあるのかどうか。