我想获取目录中最后一个文件的文件名。
例如目录'x'包含文件:
1001
1002
1003
1004
我想获取文件1004的名称,以便我可以在这样的消息框中使用它:
MsgBox("The last file is: " & FileName)
消息框显示:'最后一个文件是1004'。
任何知道如何实现这一目标的人?
答案 0 :(得分:1)
Function GetLastFile(ByVal folder As String) As String
Dim cmdOutput As String
'// Make sure folder has trailing "\"
If Right$(folder, 1) <> Application.PathSeparator Then
folder = folder & Application.PathSeparator
End If
'// Use command prompt to get a directory listing, sorted in Z-A order and read all the output into a string variable
cmdOutput = CreateObject("WScript.Shell").Exec("CMD /C DIR """ & folder & "*.*"" /A:-D /B /O:-N").StdOut.ReadAll
'// Get the first line from the output
GetLastFile = CStr(Split(cmdOutput, vbCrLf)(0))
End Function
使用示例:
MsgBox "Last file in folder is: " & GetLastFile("C:\Documents\BloggsJ\")