構文
構文は以下の通りです。
InStr([開始位置], 検索対象文字, 検索文字, [比較方法])
InStr関数は、指定した文字列内で特定の文字列を検索し、その位置を返すために使用されます。検索文字列が見つかった場合、最初に見つかった位置(1から始まる文字列の位置)を返し、見つからない場合は0を返します。
引数 | 指定 | 内容 |
開始位置 | 省略可 | 検索を開始する位置を指定します。省略すると1から検索が始まります。 |
検索対象文字 | 必須 | 検索を行う対象の文字列です。 |
検索文字 | 必須 | 検索したい文字列を指定します。 |
比較方法 | 省略可 | 文字列の比較方法を指定します。省略するとバイナリ比較が行われます。 |
使い方
具体的な使い方を幾つか紹介します。
1. 文字列内の特定の文字列を検索
Dim text As String
Dim position As Integer
text = "Hello, World!"
position = InStr(text, "World")
Dim position As Integer
text = "Hello, World!"
position = InStr(text, "World")
この例では、"Hello, World!"という文字列内で"World"を検索し、その位置をpositionに格納します。positionには6が格納されます。
2. 開始位置を指定して検索
Dim text As String
Dim position As Integer
text = "Hello, World!"
position = InStr(7, text, "World")
Dim position As Integer
text = "Hello, World!"
position = InStr(7, text, "World")
ここでは、7番目の位置以降で"World"を検索しています。この場合、positionには0が格納されます。
3. 比較方法を指定
Dim text As String
Dim position As Integer
text = "apple"
position = InStr(text, "Apples", vbTextCompare)
Dim position As Integer
text = "apple"
position = InStr(text, "Apples", vbTextCompare)
vbTextCompareを指定することで、大文字と小文字を区別しない比較が行われ、positionには1が格納されます。
プログラミング例
以下に、プログラミング例を幾つか紹介します。
例1: 文字列内のキーワードを検索して結果を表示
Sub SearchKeyword()
Dim text As String
Dim keyword As String
Dim position As Integer
text = Range("A1").Value ' A1セルから文字列を取得
keyword = "Excel" ' 検索するキーワード
position = InStr(text, keyword, vbTextCompare)
If position > 0 Then
MsgBox "キーワードが見つかりました。位置: " & position
Else
MsgBox "キーワードは見つかりませんでした。"
End If
End Sub
Dim text As String
Dim keyword As String
Dim position As Integer
text = Range("A1").Value ' A1セルから文字列を取得
keyword = "Excel" ' 検索するキーワード
position = InStr(text, keyword, vbTextCompare)
If position > 0 Then
MsgBox "キーワードが見つかりました。位置: " & position
Else
MsgBox "キーワードは見つかりませんでした。"
End If
End Sub
上記は、A1セルから文字列を取得し、指定したキーワードが含まれているかどうかを検索します。
例2: 文字列内のすべてのキーワードを検索してカウント
Sub CountKeywords()
Dim text As String
Dim keyword As String
Dim position As Integer
Dim count As Integer
text = Range("A1").Value ' A1セルから文字列を取得
keyword = "Excel" ' 検索するキーワード
count = 0
position = InStr(text, keyword, vbTextCompare)
Do While position > 0
count = count + 1
position = InStr(position + 1, text, keyword, vbTextCompare)
Loop
MsgBox "キーワード '" & keyword & "' は " & count & " 回見つかりました。"
End Sub
Dim text As String
Dim keyword As String
Dim position As Integer
Dim count As Integer
text = Range("A1").Value ' A1セルから文字列を取得
keyword = "Excel" ' 検索するキーワード
count = 0
position = InStr(text, keyword, vbTextCompare)
Do While position > 0
count = count + 1
position = InStr(position + 1, text, keyword, vbTextCompare)
Loop
MsgBox "キーワード '" & keyword & "' は " & count & " 回見つかりました。"
End Sub
上記は、指定したキーワードが文字列内で何回出現するかをカウントします。
まとめ
InStr関数は、文字列操作において非常に役立つ機能です。Excelのデータ処理やタスクの自動化を効率的に行うため、是非活用してください。