Get only the file name from MS Access file browse

…衆ロ難τιáo~ 提交于 2021-02-11 12:41:12

问题


I have the following VB code in MS Access:

Private Sub Command64_Click()
Dim dialog As FileDialog
Set dialog = Application.FileDialog(msoFileDialogFilePicker)

With dialog
    .AllowMultiSelect = False
    .Show
    Me.Thumbnail = .SelectedItems.Item(1)
End With      
End Sub

I'd like to only have the file name returned instead of the full path name. Is there a way to do this?


回答1:


Although you can't immediately return the file name from the dialog, it's relatively simple to isolate just the file name from the path that gets returned. So, once you get the path, you can do something like this to extract just the file name:

Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("C:\Temp\a_file.txt")

This will result in fileName containing "a_file.txt". Note that you must use the scripting library to access the FileSystemObject. To use it, add a reference to Microsoft Scripting Runtime (in the VBA Editor, go to: Tools > References and tick Microsoft Scripting Runtime).

For a pure VBA solution without any additional dependencies, you can create a function like this:

Public Function GetFilenameFromPath(ByVal strPath As String) As String
  If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
    GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
  End If
End Function

Given a path, it'll return just the file name:

Dim fileName As String
fileName = GetFilenameFromPath("C:\Temp\a_file.txt")

A third approach is to simply do:

Dim strPath As String
Dim fileName As String

strPath = "C:\Temp\a_file.txt"
fileName = Right$(strPath, Len(strPath) - InStrRev(strPath, "\"))

Finally, you can also use Split to get the file name from a path:

Dim strPath As String
Dim fileName As String
Dim splitList As Variant

splitList = Split(strPath, "\")
fileName = splitList(UBound(splitList, 1))

UPDATE

Using one of the simplest solutions above, your final code would look something like this:

Private Sub Command64_Click()
  Dim dialog As FileDialog
  Dim filePath As String
  Dim fileName As String

  Set dialog = Application.FileDialog(msoFileDialogFilePicker)

  With dialog
    .AllowMultiSelect = False
    .Show
    filePath = .SelectedItems.Item(1)
    fileName = Right$(filePath, Len(filePath) - InStrRev(filePath, "\"))
    'Me.Thumbnail = fileName
  End With
End Sub


来源:https://stackoverflow.com/questions/25006283/get-only-the-file-name-from-ms-access-file-browse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!