ファイル名操作関数数種
ファイル名操作を行う、こまごまとした関数の寄せ集めです。
Delphi にある同名関数を VB
でも使いたかったので自作しました。
ちょっと慣れた人なら数分で作れる程度の単純なものですが、いちいち
作っては動作確認をするのも面倒なので、まとめておきます。
'標準モジュールに記述します。 Option Explicit Public Function ExtractFilePath(S As String) As String 'ファイルパスからファイル名を取り除いたパス情報のみを返します。 Const cSep As String = "\" Dim i As Long For i = Len(S) To 1 Step -1 If Mid$(S, i, 1) = cSep Then ExtractFilePath = Left$(S, i - 1) Exit Function End If Next ExtractFilePath = S End Function Public Function ExtractFileName(S As String) As String 'ファイルパスからファイル名のみを返します。 Const cSep As String = "\" Dim i As Long For i = Len(S) To 1 Step -1 If Mid$(S, i, 1) = cSep Then ExtractFileName = Right$(S, Len(S) - i) Exit Function End If Next ExtractFileName = S End Function Public Function ExtractFileExt(S As String) As String 'ファイルパスから拡張子のみを返します。 Const cSep As String = "." Dim i As Long For i = Len(S) To 1 Step -1 If Mid$(S, i, 1) = cSep Then ExtractFileExt = Right$(S, Len(S) - i) Exit Function End If Next ExtractFileExt = "" End Function Public Function ChangeFileExt(Path As String, Ext As String) As String 'ファイルパスの拡張子部分を、第二引数で指定した文字列に置き換えます。 Const cSep As String = "." Dim i As Long For i = Len(Path) To 1 Step -1 If Mid$(Path, i, 1) = cSep Then ChangeFileExt = Left$(Path, i - 1) & cSep & Ext Exit Function End If Next ChangeFileExt = Path End Function
実行例:
'フォームにボタンを用意して、以下のプロシージャを記述します。
Private Sub Command1_Click()
Const cFullPath As String = "C:\Program Files\Dummy\DummyApp1.exe"
Debug.Print ExtractFilePath(cFullPath)
Debug.Print ExtractFileName(cFullPath)
Debug.Print ExtractFileExt(cFullPath)
Debug.Print ChangeFileExt(cFullPath, "ini")
End Sub
実行結果:
C:\Program Files\Dummy DummyApp1.exe exe C:\Program Files\Dummy\DummyApp1.ini