2017-03-07 8 views
0

私はfiledialog関数からファイルを選択し、ファイルパスをstringに格納することができます。私はまた、選択したパスのフォルダ名が必要です。選択したファイルからフォルダパスを取得する方法を教えてください。ファイルパスからフォルダパスを取得する

選択されたファイルは次のとおりです。

U:\public\2016\Macro\CD-CW\109 file.xlsx 

私はまで表示したい:

U:\public\2016\Macro\CD-CW\ 

マイコード

Dim fd As Office.FileDialog 
Set fd = Application.FileDialog(msoFileDialogFilePicker) 
With fd 
    .AllowMultiSelect = False 
    .Title = "Please select the file." 
    .Filters.Clear 
    .Filters.Add "Excel 2010", "*.xlsx" 
    .Filters.Add "All Files", "*.*" 
    If .Show = True Then 
     selfile = .SelectedItems(1) 'replace txtFileName with your textbox 
    End If 
End With 
+6

の重複[VBAでパスから最後の要素を削除する方法(http://stackoverflow.com/questions/42462625/how-to-remove-the-last-element-from-a- path-in-vba) –

+0

この質問には既に回答があります。[こちら](http://stackoverflow.com/a/42462687/4926357) –

+0

['Scripting.FileSystemObject'を使用してください。 documentation/vba/990/scripting-filesystemobject/11587/retrieve-only-the-file-from-a-file-path)を参照してください。テキストの解析よりもエラーが発生しにくいです。 – Comintern

答えて

3

これは非常に簡単です:

Dim filePath, directoryPath As String 
filePath = "U:\public\2016\Macro\CD-CW\109 file.xlsx" 
directoryPath = Left(filePath, InStrRev(filePath, "\")) 
+1

いいえ、これはちょうど起こったのではありません、どうすれば速くそれを入力できますか? –

1

LeftInStrRevの機能を使用すると、右側から最初の\の後に最後の文字列を削除できます。

Dim FilePath As String 

Dim fd As Office.FileDialog 
Set fd = Application.FileDialog(msoFileDialogFilePicker) 
With fd 
    .AllowMultiSelect = False 
    .Title = "Please select the file." 
    .Filters.Clear 
    .Filters.Add "Excel 2010", "*.xlsx" 
    .Filters.Add "All Files", "*.*" 
    If .Show = True Then 
     FilePath = Left(.SelectedItems(1), InStrRev(.SelectedItems(1), "\")) 
     Debug.Print FilePath 
     selfile = .SelectedItems(1) 'replace txtFileName with your textbox 
    End If 
End With 
+0

"Brave" downvoterが理由を説明するかもしれません –

+1

それは私ではありません。私はコメント欄で私の発言をしましたが、私は良い回答をdownvotingしていません:) –

+0

@ A.S.H私はそう思っていませんでした、ちょっと好奇心が強いのはなぜ? –

関連する問題