複数の文字列を含みかつ複数の文字列を含まない、かどうかを判断する関数
タイトルのマクロは、以下です。
'**************************************************************
'* 複数の文字列を含みかつ複数の文字列を含まない、かどうかを判断
'* str: チェック対象の文字列
'* searchStrings: str に全て含まれているべき文字列の配列
'* excludeStrings: str に含まれていてはならない文字列の配列
'* 戻り値:trueで該当、falseで非該当
Function MultipleIncludesAndExcludes(ByVal str As String, _
ByRef searchStrings() As String, _
ByRef excludeStrings() As String) As Boolean
' 判定フラグを初期化(初期値は該当するものとしてTrue)
Dim isMatche As Boolean
isMatche = True
' ループ変数の宣言
Dim i As Long
' 検索文字列が全て含まれているか確認
For i = LBound(searchStrings) To UBound(searchStrings)
' 各検索文字列がstrに含まれていない場合、判定フラグをFalseに設定
If InStr(str, searchStrings(i)) = 0 Then
isMatche = False
End If
Next i
' 除外文字列が含まれていないか確認
For i = LBound(excludeStrings) To UBound(excludeStrings)
' 各除外文字列がstrに含まれている場合、判定フラグをFalseに設定
If InStr(str, excludeStrings(i)) > 0 And excludeStrings(i) <> "" Then
isMatche = False
End If
Next i
' 判定フラグの値を関数の戻り値として返す
MultipleIncludesAndExcludes = isMatche
End Function説明
- 関数宣言部:
MultipleIncludesAndExcludes関数は、チェック対象の文字列 (str) が指定された複数の検索文字列 (searchStrings) をすべて含み、かつ複数の除外文字列 (excludeStrings) を含まないかどうかを判断します。str: チェック対象の文字列。searchStrings:strに含まれているべき文字列の配列。excludeStrings:strに含まれていてはならない文字列の配列。- 関数の戻り値は、条件を満たす場合は
True、満たさない場合はFalseです。
- 判定フラグの初期化:
isMatcheというブール型の変数を宣言し、初期値をTrueに設定します。これは、条件を満たしていると仮定しており、後の判定で条件を満たさない場合にFalseに変更されます。
- 検索文字列の確認:
Forループを使用して、searchStrings配列内の各文字列がstrに含まれているかどうかを確認します。InStr関数を使用して、各検索文字列がstrに含まれていない場合 (InStrが0を返す場合)、isMatcheをFalseに設定します。
- 除外文字列の確認:
- 同様に、
Forループを使用して、excludeStrings配列内の各文字列がstrに含まれていないかを確認します。 InStr関数を使用して、各除外文字列がstrに含まれている場合 (InStrが0より大きい値を返す場合)、かつその除外文字列が空文字列でない場合 (<> "")、isMatcheをFalseに設定します。
- 同様に、
- 戻り値の設定:
- 最後に、
isMatcheの値を関数の戻り値として返します。
- 最後に、
使用例
このマクロは、特定の文字列が複数の検索条件を満たし、かつ複数の除外条件を満たさないかどうかを判断するための使用例です。
Private Sub TestMultipleIncludesAndExcludes()
Dim searchStrings(1) As String
Dim excludeStrings(1) As String
Dim testString As String
Dim result As Boolean
' 検索文字列の配列を設定
searchStrings(0) = "test"
searchStrings(1) = "2024"
' 除外文字列の配列を設定
excludeStrings(0) = "draft"
excludeStrings(1) = "backup"
' チェックする文字列を設定
testString = "test_document_2024.xlsx"
' 関数を呼び出して結果を取得
result = MultipleIncludesAndExcludes(testString, searchStrings, excludeStrings)
Debug.Print result ' True
' チェックする文字列を設定
testString = "test_document_2023.xlsx"
' 関数を呼び出して結果を取得
result = MultipleIncludesAndExcludes(testString, searchStrings, excludeStrings)
Debug.Print result ' False。「2024」が含まれていないので、False
' チェックする文字列を設定
testString = "test_draft_2024.xlsx"
' 関数を呼び出して結果を取得
result = MultipleIncludesAndExcludes(testString, searchStrings, excludeStrings)
Debug.Print result ' False。「draft」が含まれているので、False
End SubtestString変数に"test_document_2024.xlsx"を設定し、MultipleIncludesAndExcludes関数を呼び出します。この場合、testStringは検索文字列をすべて含み、除外文字列を含まないため、結果はTrueとなります。
testString変数に"test_document_2023.xlsx"を設定し、再度関数を呼び出します。この場合、testStringは"2024"を含まないため、結果はFalseとなります。
testString変数に"test_draft_2024.xlsx"を設定し、再度関数を呼び出します。この場合、testStringは"draft"を含むため、結果はFalseとなります。


