5

我正在使用 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
4

3 回答 3

9

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

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
于 2013-02-16T21:36:04.240 回答
5

对于您想要从单击事件过程中获得的内容,无需调用单独的自定义 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
于 2013-02-17T16:30:22.700 回答
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
于 2019-12-12T17:36:27.870 回答