Excel 2010中的Dir函数VBA无法正常工作

时间:2012-07-26 17:55:10

标签: vba excel-vba automation office-automation excel

我正在尝试遍历给定目录以查找最新下载的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

test.txt文件位于我的下载文件中,filePath字符串打印出来是正确的路径,但我一直收到一条错误,指出它无法找到该文件。它在第一次使用Dir(pathToFile)时失败了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:5)

Dir()仅返回路径的文件名部分,即它不返回文件夹部分。例如,

Dir("C:\MyPath\MyFile.txt")

返回MyFile.txt而不是C:\MyPath\MyFile.txt

相关问题