2013-02-16 78 views
3

我正在使用ms訪問,我想添加一個按鈕來瀏覽文件,獲取文件的名稱及其路徑。然後我想要將文件路徑和文件名存儲在2個獨立的變量中。我目前使用的代碼位於下方,目前我可以瀏覽文件並只獲取文件的名稱。任何人都可以幫助我添加我的代碼來獲取文件路徑,並將文件名和文件路徑存儲在單獨的變量中。ms訪問瀏覽文件並獲取文件名和路徑

Private Sub Command7_Click() 

Dim f As Object 

Set f = Application.FileDialog(3) 

f.AllowMultiSelect = True 

If f.Show Then 
    For i = 1 To f.SelectedItems.Count 
     MsgBox Filename(f.SelectedItems(i)) 
    Next 
End If 

End Sub 


Public Function Filename(ByVal strPath As String) As String 

If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then 
    Filename = Filename(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1) 

End If 

End Function 

回答

7

您正在傳遞函數的完整路徑,因此您可以從中獲取路徑。例如:

Public Function Filename(ByVal strPath As String, sPath) As String 
    sPath = Left(strPath, InStrRev(strPath, "\")) 
    Filename = Mid(strPath, InStrRev(strPath, "\") + 1) 
End Function 

通過調用說:

sFile = Filename(f.SelectedItems(i), sPath) 
    MsgBox sPath & "---" & sFile 

在全

Private Sub Command7_Click() 

Dim f As Object 

Set f = Application.FileDialog(3) 

f.AllowMultiSelect = True 

If f.Show Then 
    For i = 1 To f.SelectedItems.Count 
     sFile = Filename(f.SelectedItems(i), sPath) 
     MsgBox sPath & "---" & sFile 
    Next 
End If 

End Sub 


Public Function Filename(ByVal strPath As String, sPath) As String 
    sPath = Left(strPath, InStrRev(strPath, "\")) 
    Filename = Mid(strPath, InStrRev(strPath, "\") + 1) 
End Function 
+0

嗨Remou,謝謝你的回覆。如何將文件名和文件路徑存儲在兩個單獨的變量中,我需要使用這些變量將文件複製到新文件夾中 – derek 2013-02-16 21:42:42

+0

如果查看該函數,則會發現路徑存儲在sPath中,並且文件名由Filename返回。 – Fionnuala 2013-02-16 21:44:18

+0

當我嘗試發佈前我測試過的代碼 – derek 2013-02-16 21:56:11

3

爲您從您的Click事件過程想要的東西,就沒有必要調用一個單獨的自定義VBA功能。

Private Sub Command7_Click() 
    Dim f As Object 
    Dim strFile As String 
    Dim strFolder As String 
    Dim varItem As Variant 

    Set f = Application.FileDialog(3) 
    f.AllowMultiSelect = True 
    If f.Show Then 
     For Each varItem In f.SelectedItems 
      strFile = Dir(varItem) 
      strFolder = Left(varItem, Len(varItem) - Len(strFile)) 
      MsgBox "Folder: " & strFolder & vbCrLf & _ 
       "File: " & strFile 
     Next 
    End If 
    Set f = Nothing 
End Sub 
相關問題