【VBA】文字列から指定文字より前/後ろをカットする|InStrRev/Left$/Mid$
作成日:2022-11-01
更新日:2025-10-06

指定文字列の最後の出現位置で切る
元の文字列から、指定文字より後ろの文字をカット|前を残す
' return the part before the last occurrence of strCut
' 指定文字列の最後の出現より前の部分を返す
Public Function CutAfterLastStr( _
ByVal strSrc As String, _
ByVal strCut As String) As String
Dim pos As Long
pos = InStrRev(strSrc, strCut, , vbTextCompare)
If pos = 0 Then
CutAfterLastStr = strSrc ' 見つからなければ元の文字列を返す
Else
CutAfterLastStr = Left$(strSrc, pos - 1)
End If
End Function元の文字列から、指定文字より前の文字をカット|後ろを残す
' return the part after the last occurrence of strCut
' 指定文字列の最後の出現より後の部分を返す
Public Function CutBeforeLastStr( _
ByVal strSrc As String, _
ByVal strCut As String) As String
Dim pos As Long
pos = InStrRev(strSrc, strCut, , vbTextCompare)
If pos = 0 Then
CutBeforeLastStr = strSrc ' 見つからなければ元の文字列を返す
Else
CutBeforeLastStr = Mid$(strSrc, pos + Len(strCut))
End If
End FunctionExample
| 入力文字列 | 指定文字 | 関数 | 結果 |
|---|---|---|---|
"C:\Work\Project\Report.xlsx" | "\" | CutAfterLastStr | "C:\Work\Project" |
"C:\Work\Project\Report.xlsx" | "\" | CutBeforeLastStr | "Report.xlsx" |
"user@example.com" | "@" | CutAfterLastStr | "user" |
"user@example.com" | "@" | CutBeforeLastStr | "example.com" |
Vocabulary
| Defensive Programming | 防御的プログラミング |
| Guard Clause | ガード節 |
| InStrRev Function | InStrRev関数 |
| Edge Case | エッジケース |
| Utility Function | ユーティリティ関数 |
| Intent-Revealing Code | 意図が明確なコード |
Defensive programming keeps utility functions trustworthy.
2022-11-01
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

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

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

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

クラスでForEachを使いたい 【VBA】クラスで通常のCollection機能を利用する準備|ForEachが使えない -

[VBA]開いているかwith FullName 【VBA】ブックが開いているか判定|StrComp で FullNameを調べる -

Let と Getで読み取り専用 【VBA】クラスのプロパティを読み取り専用にするLet と Getの書き方