【VBA】拡張子の存在確認|Right + StrComp
作成日:2022-11-01
更新日:2025-09-29

StrCompで
文字列比較しよう
文字列比較しよう

StrComp?

2つの文字列が同じかどうかを比較する
指定の文字列の末尾に、指定の拡張子があればtrueを返す

Right と StrComp の組み合わせで判定する
' StrComp returns 0 when equal
' StrComp は一致なら 0 を返す
Public Function ExtensionExists( _
ByVal targetName As String, _
ByVal expectedExtension As String) As Boolean
ExtensionExists = (StrComp( _
Right$(targetName, Len(expectedExtension)), _
expectedExtension, _
vbTextCompare) = 0)
End FunctionRight$→ 文字列の末尾を切り出す(語尾一致チェック)。StrComp(..., vbTextCompare)→ 大文字小文字を無視して比較。- 結果が
0なら等しい →True。
StrComp(..., vbTextCompare)
StrComp is a VBA function used to compare two strings.

2つの文字列を比較するための関数
StrComp("ABC", "abc", vbTextCompare) ' → 0 (等しい)
StrComp("Dog", "Cat", vbTextCompare) ' → 1 (Dog > Cat)
StrComp("apple", "Banana", vbTextCompare) ' → -1 (apple < Banana)文字列比較関数(文字列を比較する関数)
vbTextComparetells VBA to compare strings without case sensitivity (ignoring uppercase/lowercase differences).vbTextCompareを指定すると、文字列を 大文字小文字を区別せずに比較 する
- 結果は単純で「等しいなら
0、違えば -1 または 1」。
語尾一致だけを判定したい場合
StrComp自体は「全文字列比較」であり、「語尾だけ一致」判定機能は持っていない。- 語尾一致を判定したいなら、
Rightと組み合わせる。
Dim word As String
word = "HelloWorld"
If StrComp(Right(word, 5), "world", vbTextCompare) = 0 Then
Debug.Print "語尾が一致!"
End IfReferenced Insights & Citations
- Microsoft Docs. StrComp function
Vocabulary
| Case-insensitive | 大文字小文字を無視 |
| Extension | 拡張子 |

同じ処理をPythonでも書いてみよう
2022-11-01
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[VBA]Cutbefore after 【VBA】文字列から指定文字より前/後ろをカットする|InStrRev/Left$/Mid$ -

数値に+ 記号を追加 【VBA】正の数値に+記号を追加|Sgn -

UsedRangeのデータを配列で取得 【VBA】シートにあるデータを配列に格納する(空白含む)|UsedRange -

[VBA]開いているかwith FullName 【VBA】ブックが開いているか判定|StrComp で FullNameを調べる -

文字の位置を取得 【VBA】文字列から指定文字の位置を取得する|InStr/InStrRev -

[VBA]CreateObjectまとめ 【VBA】CreateObject|dictionary・テキストファイル・outlook・Access用にオブジェクトを生成する