【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]Control the calculation再計算 【VBA】指定のシートを再計算する|Calculate -

[VBA]StrCompで文字列比較 【VBA】拡張子の存在確認|Right + StrComp -

[VBA]extract the filename 【VBA】フルパスからファイル名と拡張子を取得する -

[VBA]close booksave or not 【VBA】ブックを閉じる3つの方法|保存して/保存しないで/ブック名で/ -

[VBA]get fso objectfrom path 【VBA】パスからfsoオブジェクトを取得する|fso.GetFolder/.GetFile -

[VBA]画像として貼り付けCopyPicture 【VBA】セル範囲を画像としてコピーする|CopyPicture