我在MS Access中有以下VB代码:
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
我想只返回文件名而不是完整路径名。有没有办法做到这一点?
答案 0 :(得分:1)
虽然您无法立即从对话框中返回文件名,但仅将文件名与返回的路径隔离起来相对简单。因此,一旦获得路径,就可以执行类似这样的操作来提取文件名:
Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("C:\Temp\a_file.txt")
这将导致fileName
包含“a_file.txt”。请注意,您必须使用脚本库来访问FileSystemObject
。要使用它,请添加对 Microsoft Scripting Runtime 的引用(在VBA编辑器中,转到:工具>参考并勾选 Microsoft Scripting Runtime )。
对于没有任何其他依赖关系的纯VBA解决方案,您可以创建如下函数:
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
给定一个路径,它只返回文件名:
Dim fileName As String
fileName = GetFilenameFromPath("C:\Temp\a_file.txt")
第三种方法是简单地做:
Dim strPath As String
Dim fileName As String
strPath = "C:\Temp\a_file.txt"
fileName = Right$(strPath, Len(strPath) - InStrRev(strPath, "\"))
最后,您还可以使用Split
从路径中获取文件名:
Dim strPath As String
Dim fileName As String
Dim splitList As Variant
splitList = Split(strPath, "\")
fileName = splitList(UBound(splitList, 1))
<强>更新强>
使用上面最简单的解决方案之一,您的最终代码将如下所示:
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