0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Excel VBA】StrComp関数|文字列を比較する方法と結果の見方・注意点

Last updated at Posted at 2025-08-19

この記事ではStrComp関数の使い方と注意点について解説します。
他のよく使うVBA関数一覧はこちら。

StrComp関数の使い方と注意点

StrComp関数は、2つの文字列を比較して、その一致・大小関係を判定する関数です。
大文字・小文字を区別するかどうかも指定できます。

構文

StrComp(文字列1, 文字列2 [, 比較方法])
  • 文字列1 / 文字列2 : 比較対象の2つの文字列
  • 比較方法(省略可) : 比較方法を表す定数や数値
  • 戻り値 : 比較結果を整数で返します。

比較方法を表す定数

定数 内容
-1または省略 vbUseCompareOption Option Compare の設定に従う
0 vbBinaryCompare バイナリ比較
1 vbTextCompare テキスト比較

戻り値の種類

意味
0 等しい
-1 文字列1 < 文字列2
1 文字列1 > 文字列2
Null いずれかがNullの場合(比較不可)

使用例

大文字小文字を無視して比較

Sub Sample()
    Dim result As Integer
    result = StrComp("sampletext", "sampletext", vbTextCompare)
    Debug.Print result
End Sub

▶ 出力結果

0

大文字小文字を区別して比較

Sub Sample()
    Dim result As Integer
    result = StrComp("Sampletext", "sampletext", vbBinaryCompare)
    Debug.Print result
End Sub

▶ 出力結果

-1

Nullの比較

Sub Sample()
    Dim str1 As String
    Dim str2 As Variant
    str1 = "test"
    str2 = Null

    Debug.Print StrComp(str1, str2)
End Sub

▶ 出力結果

Null

⚠️注意

Nullが含まれると戻り値もNullになる

文字列のどちらかがNullの場合、比較結果もNullになります。
この場合はIsNull関数などで事前チェックを行いましょう。

Sub Sample()
    Dim str1 As String
    Dim str2 As Variant
    Dim result As Integer

    str1 = "test"
    str2 = Null

    If Not IsNull(str1) And Not IsNull(str2) Then
        result = StrComp(str1, str2)
        Debug.Print result
    End If
End Sub

Option Compareの影響を受ける(比較方法省略時)

比較方法の引数を省略すると、モジュールの先頭にあるOption Compareの設定が適用されます。

Option Compare Text

Sub Sample()
    Debug.Print StrComp("A", "a")
End Sub

▶ 出力結果

0
Option Compare Binary

Sub Sample()
    Debug.Print StrComp("A", "a")
End Sub

▶ 出力結果

-1

Option Compareの設定が意図しない比較を引き起こすことがあるため、compare引数は明示的に指定するのがおすすめです。

その他のVBA関数

【Excel VBA】VBAでよく使う関数一覧&基本の使い方

参考リンク

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?