der*_*ble 5 excel automation vba excel-vba office-automation
我试图循环一个给定的目录,以找到最新下载的csv文件.由于某种原因,即使文件存在,我的Dir函数也找不到任何文件.我对VBA并不完全熟悉,所以我可能会错过某种执行Dir功能的参考,但我找不到任何在线告诉我需要的东西.所有的例子和论坛都像我一样使用Dir,但我不能让我的工作.这是代码,如果你能看到我做错了,请告诉我:
Public Function Get_File() as string
Dim filePath As String
ChDir ("..")
filePath = CurDir
'Goes back to Documents directory to be in same directory as macro
ChDir (filePath & "\Documents")
filePath = filePath & "\Downloads\test.txt"
filePath = getLatestFile(filePath)
Get_File = filePath
End Function
Public Function getLatestFile(pathToFile As String) As String
Dim StrFile As String
Dim lastMod As Variant
Dim nextMod As Variant
Dim lastFileName As String
StrFile = Dir(pathToFile)
lastFileName = StrFile
lastMod = FileDateTime(StrFile)
While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
nextMod = FileDateTime(StrFile)
If nextMod > lastMod Then
lastFileName = StrFile
lastMod = nextMod
End If
Wend
getLatestFile = lastFileName
End Function
Run Code Online (Sandbox Code Playgroud)
test.txt文件位于我的下载文件中,filePath字符串打印出来是正确的路径,但我一直收到一条错误,指出它无法找到该文件.它在第一次使用Dir(pathToFile)时失败了.任何帮助将不胜感激.
Dir()只返回路径的文件名部分,即它不返回文件夹部分.例如,
Dir("C:\MyPath\MyFile.txt")
Run Code Online (Sandbox Code Playgroud)
MyFile.txt没有回报C:\MyPath\MyFile.txt
| 归档时间: |
|
| 查看次数: |
10240 次 |
| 最近记录: |