構文
構文は以下の通りです。
Instr([開始位置], 検索対象文字列, 検索文字列, [比較方法])
解説
Instr関数は、指定した文字列内で特定の文字列を検索し、その位置を返す関数です。検索文字列が見つかった場合はその位置を返し、見つからなかった場合は0を返します。
引数 | 指定 | 内容 |
開始位置 | 省略可 | 検索を開始する位置を指定します。省略すると1(先頭)から検索が始まります。 |
検索対象文字列 | 必須 | 検索を行う文字列を指定します。 |
検索文字列 | 必須 | 検索する文字列を指定します。 |
比較方法 | 省略可 | 文字列の比較方法を指定します。省略するとバイナリ比較が行われますが、日本語の場合はvbBinaryCompareを指定することが多いです。 |
使用例
InStr("Excel", "E")
InStr("Excel", "ce")
InStr(6, "excel", "e")
使い方
具体的な使い方を紹介します。
例1: 文字列内の特定の文字の位置を検索する
Dim text As String
text = "Hello, world!"
Dim position As Integer
position = Instr(text, "world")
text = "Hello, world!"
Dim position As Integer
position = Instr(text, "world")
上記のコードを実行すると、変数positionには文字列"world"が始まる位置が格納されます。
例2: 特定の文字列が含まれているかを判定する
Dim sentence As String
sentence = "I love programming!"
Dim result As Boolean
result = (Instr(sentence, "love") > 0)
sentence = "I love programming!"
Dim result As Boolean
result = (Instr(sentence, "love") > 0)
上記のコードを実行すると、変数resultには文字列"love"が含まれているかどうかがTrueまたはFalseで格納されます。Trueの場合は含まれており、Falseの場合は含まれていません。
プログラミング例
以下に、プログラミング例を紹介します。
Dim text As String
Dim searchString As String
Dim count As Integer
Dim position As Integer
text = "This is a sample text."
searchString = "is"
count = 0
position = 1
Do While position > 0
position = Instr(position, text, searchString)
If position > 0 Then
count = count + 1
position = position + 1
End If
Loop
MsgBox "文字列 """ & searchString & """ は " & count & " 回出現します。"
Dim searchString As String
Dim count As Integer
Dim position As Integer
text = "This is a sample text."
searchString = "is"
count = 0
position = 1
Do While position > 0
position = Instr(position, text, searchString)
If position > 0 Then
count = count + 1
position = position + 1
End If
Loop
MsgBox "文字列 """ & searchString & """ は " & count & " 回出現します。"
上記のコードでは、文字列"searchString"が文字列"text"内でいくつ出現するかを数える例です。Instr関数をDo Whileループと組み合わせて使用し、出現回数を変数"count"に格納しています。
まとめ
Instr関数は、特定の文字列の位置検索や含まれているかの判定を行います。是非活用してください。