VBA:如何在不参考文件path的情况下需要某个文件名?

我需要用户select一个特定的文件名,但文件可能在不同的文件夹或驱动器取决于谁使用它,所以path并不重要。 我尝试使用星号的path,但它不工作。 有什么build议么? 该文件将始终命名为“2016 latest.txt”,“2017 latest.txt”等。我希望上传的下一个文件始终顺序,这就是为什么我有代码中的“LastYear + 1”。 至于path,文件的来源应该不重要,只有名字。

Dim LastYear As String LastYear = Worksheets("Main Menu").Cells(1, "B").Value Dim fName As String fName = Application.GetOpenFilename("Text Files (*.txt), *.txt") If fName = "False" Then Exit Sub If fName <> "*" & LastYear + 1 & " latest.txt" Then MsgBox "Wrong File. Please choose " & LastYear + 1 & " file." Exit Sub End If 

你可以随时让用户select文件:

 Sub GetFile() Dim fNameAndPath As Variant fNameAndPath = Application.GetOpenFilename(FileFilter:="All Files (*.*), *.*", Title:="Select File To Be Opened") Debug.Print fNameAndPath Debug.Print Dir(fNameAndPath) If Dir(fNameAndPath) = "yourFileName" Then 'correct file else 'wrong file endif End Sub 

或者你可以通过文件系统search特定的文件,但这可能会更困难(权限,巨大的文件系统等)。 正如@Masoud所说,如果path不在当前文件夹中,path需要被提供。

编辑:如果你想让用户只select文本文件,然后更换

 FileFilter:="All Files (*.*), *.*" 

 FileFilter:="Text Files (*.txt), *.txt" 

Like运算符可用于模式匹配:

 Dim fName, y fName = Application.GetOpenFilename("Text Files (*.txt), *.txt") y = ['Main Menu'!B1 + 1] If Not fName Like "*\" & y & " latest.txt" Then If fName <> False Then MsgBox "Wrong File. Please choose " & y & " file." Exit Sub End If