Excel 2010 VBA 中的目录函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11675162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dir Function in Excel 2010 VBA not working
提问by derigible
I am trying to loop through a given directory to find the latest downloaded csv file. For some reason my Dir function won't find any file even if the file does exist. I am not totally familiar with VBA so i may perhaps be missing some sort of reference to perform the Dir function, but I can't find anything online that tells me I need to. All the examples and forums use Dir just like I do, but I can't get mine to work. Here is the code, please tell me if you can see what I am doing wrong:
我正在尝试遍历给定目录以查找最新下载的 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
The test.txt file is in my Downloads file and the filePath string prints out to be the correct path, but I keep getting an error stating that it can't find the file. It fails at the first use of Dir(pathToFile). Any help would be greatly appreciated.
test.txt 文件在我的下载文件中,filePath 字符串打印出来是正确的路径,但我不断收到错误消息,指出它找不到该文件。它在第一次使用 Dir(pathToFile) 时失败。任何帮助将不胜感激。
采纳答案by mwolfe02
Dir()
only returns the filename portion of the path, i.e., it does not return the folder portion. For example,
Dir()
只返回路径的文件名部分,即不返回文件夹部分。例如,
Dir("C:\MyPath\MyFile.txt")
returns MyFile.txt
not C:\MyPath\MyFile.txt
MyFile.txt
不返回C:\MyPath\MyFile.txt