【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]Paste 2D Arrayresize once 【VBA】二次元配列をシートに貼り付け【範囲をリサイズする】 -

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

[VBA]InStr文字列確認 【VBA】指定の文字列が含まれているか & 前後の文字列を返す|InStr/InStrRev -

[VBA]Reset filtersand outlines 【VBA】オートフィルタ解除&非表示を表示する|.FilterMode/.Outline -

[VBA]Redim とRedim Preserve 【VBA】配列の要素数を決める|ReDim vs ReDim Preserve & Pythonとの違い -

[VBA]Vertical Paste1D array 【VBA】一次元配列を縦方向にシートに貼り付け【範囲をリサイズする】