excelvba

Dir Function to find file


I am trying to loop through a given directory to find the latest downloaded csv file.

The Dir function won't find the existing file.

Here is the code:

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 folder and the filePath string prints out the correct path.

I get an error stating that it can't find the file.

It fails at the first use of Dir(pathToFile).


Solution

  • Dir() only returns the filename portion of the path, i.e., it does not return the folder portion. For example,

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

    returns MyFile.txt not C:\MyPath\MyFile.txt