vba - Excel 2010 VBA 中的 Dir 函数不起作用

标签 vba excel automation 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

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

最佳答案

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

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

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

关于vba - Excel 2010 VBA 中的 Dir 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675162/

相关文章:

c# - 如何在文档级加载项中将 C# 类公开给 VBA 模块?

mysql - Access 查询分组/求和

excel - 以编程方式确定 Excel 文件 (.xls) 是否包含宏

automation - 机械手框架:套件设置和测试设置之间的区别?

scripting - Adobe Premiere 脚本

android - 使用顺序测试用例的最佳实践是什么?

excel - UDF 随机数生成器类型不匹配

vba - 打开多个 Excel 文件时,为 Excel 文件中的单元格设置值会出现错误

excel - 如何使用 Excel VBA 在运行时打开 MS Access?

excel - InStr 值数组(可能?)