0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【VBA】3個以上のキーワードでAutoFilterを利用する場合

Posted at

背景

  • データ加工の際に、以下の仕様にしたいため、可能かどうか調査。
    • AutoFilterに設定するキーワードを3つ以上にしたい。
    • 設定するキーワードは、シート内に記述して、そこから追加や削除を行えるようにしたい。
    • キーワードは完全一致検索で行う。
  • 今回は作業列を利用した配列でのオートフィルター設定を記述。

結果

  • 以下のようなデータとキーワードが入ったシート2つを用意する。
    • ※指定キーワードの追加や削除をSheet2だけで行えるように、「キーワード数」はcount関数等で取っておく。

image.png

image.png

  • 以下のVBAを記述する。
Sub main()
    ' 変数定義
    Dim ws1 As Worksheet, ws2 As Worksheet, targetnumber As Long, targetArray
    Set ws1 = Sheets("Sheet1")
    Set ws2 = Sheets("Sheet2")
    targetnumber = ws2.Range("B2")  ' キーワード数
    ' キーワードの配列変換処理。セル範囲を二次元配列から一次元配列に変換
    targetArray = WorksheetFunction.Transpose(ws2.Range("A2:A" & targetnumber + 1))
    ' オートフィルター処理
    ws1.Range("A1").AutoFilter 2, targetArray, xlFilterValues
End Sub
  • 上記のmain関数を実行して、以下のような結果になっていれば完了。

image.png

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?