从技术上讲,这并不完全符合您的要求,但让用户在其中选择文件是一种更好的编程实践
操作系统界面,而不是让他们输入文件名,
最终达到相同的目标。
我创建了一个自定义函数,用于通过FileDialog 对象选择文件。作为可选参数,您可以在 format 参数中强制执行特定的文件类型。
get_file([format], [fullpath])
' Returns a file name of a selected file via the .FileDialog object
' Arguments:
' [format] : Optional argument, if left empty any file format can be selected, _
otherwise enforce what [format] was put in to be selected
' [fullpath] : Optional argument, if left empty will only return FileName.xxx, _
otherwise will return full path (eg. D:\MyDir\Book.xlsx")
' Returns: A <String> with the selected filename.
函数如下所示:
Private Function get_file(Optional ByVal format As String = "nomatch", _
Optional ByVal fullpath As Boolean = False) As String
Dim fs As FileDialog: Set fs = Application.FileDialog(msoFileDialogFilePicker)
Dim goodmatch As Boolean: goodmatch = False
Do Until goodmatch = True
With fs
If .Show <> -1 Then
.Title = "Choose a Workbook to work with"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
End If
If format = "nomatch" Then
goodmatch = True
Else
format = Replace(format, ".", "")
If Mid(.SelectedItems(1), InStrRev(.SelectedItems(1), ".") + 1) <> format Then
MsgBox "Please select a " & format & " file format", vbCritical
Else
goodmatch = True
End If
End If
End With
Loop
If fullpath = True Then
get_file = fs.SelectedItems(1)
Else
get_file = Mid(fs.SelectedItems(1), InStrRev(fs.SelectedItems(1), "\") + 1)
End If
End Function
函数的示例用户:
Private Sub test()
Dim wb As Workbook: Set wb = Workbooks.Open(get_file(".xlsx", fullpath:= True))
' saves a workbook of only .xlsx type from what user selected into wb variable
Debug.Print wb.Name
End Sub
使用 [fullpath] 打开工作簿以获得正确的链接 (True) 和强制执行的 .xlsx [format] 并打印保存在 wb 变量中的 Workbook 对象的 Name 属性