[Excel VBA] How to AutoFilter with “Contains” and “Does Not Contain” Conditions (Wildcard Guide)

目次

Overview

Excel allows you to specify wildcards (* or ?) in AutoFilter to extract only rows that contain or do not contain specific strings. In this article, I will carefully explain the basics and applications of wildcard specifications using VBA implementation examples.

Prerequisites

ItemContent
ExcelMicrosoft 365 or 2016 and later
Data RangeAssumes a table including a header row is at F3:I100
Macro LocationStandard Module

Sample Code (VBA)

1. Example: Extract rows containing a specific string

Sub FilterContainsKeyword()

    Dim tblRange As Range              ' Filter target
    Set tblRange = Worksheets("Sheet1").Range("F3").CurrentRegion   ' Range including header row
    
    '--- Extract rows containing "Mori" in Column 4 (Col H) ---
    tblRange.AutoFilter Field:=4, Criteria1:="=*Mori*"
    
End Sub

2. Example: Extract rows NOT containing a specific string

Sub FilterExcludesKeyword()

    Dim tblRange As Range
    Set tblRange = Worksheets("Sheet1").Range("F3").CurrentRegion
    
    '--- Extract rows NOT containing "Mori" in Column 4 (Col H) ---
    tblRange.AutoFilter Field:=4, Criteria1:="<>*Mori*"
    
End Sub

Key Points of the Code

LineDescription
3Retrieves the entire table (including headers) using CurrentRegion. Change the starting cell according to your actual data.
6"*Mori*" is a wildcard expression that extracts only cells containing “Mori”. The * represents any string of characters.
12Using <>*Mori* extracts only cells that do not contain “Mori”. The <> symbol represents the “Not Equal” condition.

Application Examples

PurposeImplementation Hint
Extract multiple keywords with ORCriteria1:=Array("*Mori*", "*Hayashi*"), Operator:=xlFilterValues
Composite extraction with ANDIf you apply conditions to different columns in subsequent AutoFilter commands, it becomes an AND condition.
Case sensitivityExecute Application.MatchCase = True before setting the filter (Set it back to False after processing).

FAQ

Q. What is the difference between the wildcards ? and *?

A. * represents any string of 0 or more characters, while ? represents any single character. They offer different flexibility for partial matching.

Q. How do I copy only the visible cells after extraction?

A. You can handle only the visible cells by using tblRange.SpecialCells(xlCellTypeVisible).Copy.

Summary

By using AutoFilter settings with wildcards, you can immediately extract rows that contain or do not contain specific strings.

First, run the sample macro and confirm that the expected rows are displayed. You can apply this to various datasets simply by changing the keywords and column numbers, so please use it to improve your work efficiency.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次