銀河鉄道

【VBA】文字列から指定文字の位置を取得する|InStr/InStrRev

サムネイル
文字の位置取得
位置は
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

方針

  • InStrInStrRev の両方を統一的に扱えるようにする
  • 一致しなければ 0 を返す(VBA標準の仕様と整合)
  • 構造的整合性のため、FindOrigin Enum を再利用する

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

Vocabulary

| FindPos|位置取得関数 |
| InStrRev|逆方向検索 |
| Compare Method|比較方法 |
| Responsibility Separation|責務分離 |
| Structural Anchor|構造の支点 |

The position is the structure’s root.
Before slicing strings, always locate their anchor.

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧