问题
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