【Word VBA】選択したファイルの「ファイルパス」と「フォルダパス」をゲットするWordマクロ

2010年10月21日

これ、プログラミングをしていて迷うので、案外便利だと思います。

かなり無理矢理感がありますが、なんとか

フォルダパス
ファイルパス
ファイル名

を取り出しています。

ここで活躍するのが文字列関数
ようやく、具体的な使い方を紹介できました。

Right関数
Left関数
Len関数

もう少し別の書き方があるのかな?

慣例的な取得方法がありそうな気もしますが、
ちょっとクイズみたいに思って勝手に作ってしまいました。

どうなるか?

①このようなファイル選択ダイアログが表示されます。

ファイルパス、フォルダパス

②選んだファイルの
・フォルダパス
・ファイルパス
・ファイル名
がメッセージボックスに表示されます。

ファイルパス、フォルダパス

プログラム

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Sub FilePath_FolderPath()
 
'簡易版
Dim fd As FileDialog
Dim myFileName As String
Dim myFolderPath As String
Dim myFilePath As String
 
  On Error GoTo EH
 
Set fd = Application.FileDialog(msoFileDialogOpen)
 
With fd
  .Title = "ファイルを1つ選んでください。"
  .AllowMultiSelect = False
  If .Show = -1 Then
    myFilePath = .SelectedItems(1)
    myFileName = Right(myFilePath, Len(myFilePath) - InStrRev(myFilePath, "\"))
    myFolderPath = Left(myFilePath, Len(myFilePath) - Len(myFileName) - 1)
 
    MsgBox "フォルダパス:" & myFolderPath & vbCr & _
        "ファイルパス:" & myFilePath & vbCr & _
        "ファイル名:" & myFileName
  End If
End With
 
Set fd = Nothing
 
  On Error GoTo 0
  Exit Sub
 
EH:
 
  MsgBox Err.Description
 
End Sub

関連記事

文字列関数の目次

-コード
-, , ,

S