在excel中,msoFileDialogFilePicker将返回一个文件名及其路径,我想要的只是文件名。以下是返回两者的代码:
Sub GetfileNames()
Dim fd As FileDialog
dialogTitle = "Select files for Master Update."
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.InitialFileName = "H:\Desktop\Workforce Project Documents\Update Sandbox\"
.AllowMultiSelect = True
.Filters.Clear
.Title = dialogTitle
.InitialView = msoFileDialogViewDetails
'This MSG is displayed if the user dose not select a file
If .Show = False Then
MsgBox "Files not selected to update. Process Terminated"
Exit Sub
End If
'vrtSelectedItem = .SelectedItems(1)
'vrtSelectedItem = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
For Each vrtSelectedItem In .SelectedItems
MsgBox "Selected file's name is: " & vrtSelectedItem
'MsgBox "Selected file's name is: " '& vrtSelectedItem = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
Next
'MsgBox "Selected File's name is: " & vrtSelectedItem
End With
End Sub
您会注意到我已注释掉该行:
'MsgBox "Selected file's name is: " '& vrtSelectedItem = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
除去路径,因为当我使用它时,它返回单词' false'另外值得注意的是,当我将.AllowMultiSelect设置为false并且只引入一个值时,它工作正常,我只得到文件名。任何人都可以看到有什么问题?以下是单个变量的代码。
Sub GetfileNames()
Dim fd As FileDialog
dialogTitle = "Select files for Master Update."
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.InitialFileName = "H:\jpmDesk\Desktop\Workforce Project Documents\Update Sandbox\"
.AllowMultiSelect = False
.Filters.Clear
.Title = dialogTitle
.InitialView = msoFileDialogViewDetails
'This MSG is displayed if the user dose not select a file
If .Show = False Then
MsgBox "Files not selected to update. Process Terminated"
Exit Sub
End If
vrtSelectedItem = .SelectedItems(1)
vrtSelectedItem = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
MsgBox "Selected File's name is: " & vrtSelectedItem
End With
End Sub
答案 0 :(得分:1)
考虑使用 Split()
Sub GetTheName()
Dim s1 As String, s2 As String
s1 = "C:\financial\archive\2013\taxes\FirstQuarter.xlsm"
ary = Split(s1, "\")
s2 = ary(UBound(ary))
MsgBox s2
End Sub