2015-08-18 85 views
2

我正在編寫一個代碼,其中我正在打開一個用於提取數據的文件。我目前使用下面的代碼;我想從路徑中提取文件名並將其存儲在特定範圍內。此代碼:如何從其路徑中提取文件名vba

FilePath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xls") 
If FilePath <> False Then 
Range("D6").Value = FilePath 
file = Range("D6").Value 
Range("D6").Clear 
End If 
+0

你說「我想要從路徑中提取文件名並將其存儲在特定範圍內「你清除D6。那麼你想在後面的代碼中使用'file = Range(「D6).value'做些什麼**並且**你希望D6只有文件名而沒有它的路徑? –

+0

是的,我使用了它並且它工作得很好 strName = Right(FilePath,Len(FilePath) - InStrRev(FilePath,「\」)) 然後我將strName指定給Range並使用相同的值 – Ansh

回答

2

你可以像下面:

FilePath = Application.GetOpenFilename("Excel Files (*.xlsm), *.xlsm") 

If FilePath <> False Then 
    Dim fso As Object 
    Dim objFile As Object 

    Set fso = VBA.CreateObject("Scripting.FileSystemObject") 
    Set objFile = fso.GetFile(FilePath) 

    If Not objFile Is Nothing Then 
     FileName = objFile.Name 
    End If 

End If 
+0

感謝它解決了我的問題:) – Ansh

2

一種替代方案:

Public Function ExtractFileName(ByVal strFullName As String) As String 

Dim p As Integer 
Dim i As Integer 
Dim s As Integer 

i = 1 
Do 
    p = InStr(i, strFullName, "\", 1) 
    If p = 0 Then Exit Do 
    s = p 
    i = p + 1 
Loop 
s = s + 1 
ExtractFileName = Mid(strFullName, s, Len(strFullName)) 

End Function  'ExtractFileName 
1

最簡單的方法:

FileName = Mid$(FilePath, InStrRev(FilePath, "\") + 1, Len(FilePath)) 
相關問題