【问题标题】:Dir Function in Excel 2010 VBA not workingExcel 2010 VBA中的Dir函数不起作用
【发布时间】:2012-07-25 09:15:34
【问题描述】:

我正在尝试遍历给定目录以查找最新下载的 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) 时失败。任何帮助将不胜感激。

【问题讨论】:

  • 错误与 DIR 无关。错误在于这一行lastMod = FileDateTime(StrFile) 您必须提供完整路径。其他人也是如此。

标签: vba excel automation office-automation


【解决方案1】:

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

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

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

【讨论】:

  • 好的,做到了。感谢您的回答,我不知道这是 Dir 的情况。 Excel 中的帮助部分指出,但出于某种原因,我认为它会返回整个路径。这又为我节省了几个小时。
猜你喜欢
  • 2014-04-02
  • 2012-04-20
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多