ms访问浏览文件并获取文件名和路径

时间:2013-02-16 21:14:27

标签: vba ms-access

我正在使用ms访问,我想添加一个按钮来浏览文件,获取文件的名称及其路径。然后我想将文件路径和文件名存储在2个单独的变量中。我到目前为止的代码是在下面,目前我可以浏览文件并只获取文件的名称。任何人都可以帮我添加我的代码来获取文件路径并将文件名和文件路径存储在单独的变量中。

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

3 个答案:

答案 0 :(得分:8)

您正在传递函数的完整路径,因此您可以从中获取路径。例如:

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

答案 1 :(得分:4)

对于您想要的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

答案 2 :(得分:0)

我用来加载Excel文件的另一种方法:

Public Sub Command7_Click()
    Dim FD As FileDialog
    Dim fileNamePath As String, fileExtension As String, fileName As String
    If fileNamePath = "" Then
        Set FD = Application.FileDialog(msoFileDialogOpen)
        Dim FileChosen As Integer
        FileChosen = FD.show
        FD.Title = "Choose workbook"
        FD.InitialView = msoFileDialogViewList

        FD.Filters.Clear
        FD.Filters.Add "Excel workbooks", "*.xlsx"
        FD.Filters.Add "All files", "*.*"
        FD.FilterIndex = 1
        FD.ButtonName = "Choose this file"
        If FileChosen <> -1 Then 'didn't choose anything (clicked on CANCEL)
            MsgBox "No file opened", vbCritical
        Else
            fileNamePath = FD.SelectedItems(1)
            fileName = Dir(fileNamePath)
            fileExtension = Right$(fileName, Len(fileName) - InStrRev(fileName, "."))
        End If
        Set FD = Nothing
    End If
End Sub
相关问题