銀河鉄道

【VBA】拡張子の存在確認|Right + StrComp

サムネイル
[VBA]StrCompで文字列比較
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 Function
  • Right$ → 文字列の末尾を切り出す(語尾一致チェック)。
  • 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)
文字列比較関数(文字列を比較する関数)
  • vbTextCompare tells 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 If

Referenced Insights & Citations

Vocabulary

Case-insensitive大文字小文字を無視
Extension拡張子

同じ処理をPythonでも書いてみよう

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧