【VBA】文字列から指定文字の位置を取得する|InStr/InStrRev
作成日:2022-11-01
更新日:2025-10-06

位置は
position
position
指定文字の位置を取得して、その番号を返す
' return the position of keyword (first/last occurrence selectable)
' 指定語の出現位置を返す(最初/最後の選択可能)
Public Function FindPos( _
ByVal targetString As String, _
ByVal keyword As String, _
Optional ByVal origin As FindOrigin = FromStart, _
Optional ByVal compare As VbCompareMethod = vbTextCompare) As Long
Dim p As Long
' Determine search direction|検索方向を決定
If origin = FromEnd Then
p = InStrRev(targetString, keyword, -1, compare)
Else
p = InStr(1, targetString, keyword, compare)
End If
FindPos = p ' 位置を返す(見つからなければ0)
End Function
方針
InStr/InStrRevの両方を統一的に扱えるようにする- 一致しなければ
0を返す(VBA標準の仕様と整合) - 構造的整合性のため、
FindOriginEnum を再利用する

InStrについてはこちらで
Example Usage
Debug.Print FindPos("C:\Data\report.xlsx", "\") '→ 3
Debug.Print FindPos("C:\Data\report.xlsx", "\", FromEnd) '→ 7
Debug.Print FindPos("Report", "port") '→ 3
Debug.Print FindPos("Report", "PORT", , vbTextCompare) '→ 3 (大文字小文字無視)
Structural Note|構造上の位置付け
この FindPos は「抽出系(LeftOf/RightOf)」の前段階として機能する。
つまり、
FindPos→ 「位置を得る」LeftOf/RightOf→ 「内容を得る」
という明確な責務分離
References
- Microsoft Docs: InStr function (VBA)
- Microsoft Docs: InStrRev function (VBA)
Vocabulary
| FindPos|位置取得関数 |
| InStrRev|逆方向検索 |
| Compare Method|比較方法 |
| Responsibility Separation|責務分離 |
| Structural Anchor|構造の支点 |
The position is the structure’s root.
Before slicing strings, always locate their anchor.
Before slicing strings, always locate their anchor.
2022-11-01
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[VBA]Resizerows and columns 【VBA】Resize changes the size of a cell range|範囲のリサイズ -

[VBA]Cells or Range 【VBA】.Cells と .Range の使い分け目安|数千か数万か -

dictionaryをセットする 【VBA】Dictionaryのセット|CreateObject(“Scripting.Dictionary”) -

[VBA]buttonに何が登録されてるか 【VBA】ボタンに登録されているマクロ名を調べたい -

[VBA]開始と終了イベント停止と再開 【VBA高速化】開始と終了のルーチン呼び出し -

CurrentRegionのデータを配列で取得 【VBA】シートにあるデータを配列に格納する(空白含まない)|CurrentRegion