0

I'm pretty new to VBA but I am trying to learn a lot more. Right now I'm trying to code a macro to open the most recent file in my :Z drive that is a comma delimited file (.CSV). The below code doesn't work but I was wondering if anyone had any advice? thanks for you help!

Sub NewestFile()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date

MyPath = "Z:\"
If Right(MyPath, 1) <> “ \ ” Then MyPath = MyPath & “ \ ”
  MyFile = Dir(MyPath & “ * .csv”, vbNormal)
  If Len(MyFile) = 0 Then
    MsgBox “No files were found…”, vbExclamation
    Exit Sub
  End If
  Do While Len(MyFile) > 0
    LMD = FileDateTime(MyPath & MyFile)
    If LMD > LatestDate Then
      LatestFile = MyFile
      LatestDate = LMD
    End If
    MyFile = Dir
  Loop
  Workbooks.Open MyPath & LatestFile
End Sub
braX
  • 11,506
  • 5
  • 20
  • 33
The Dude MAN
  • 47
  • 1
  • 1
  • 9

1 Answers1

0

Here you go. Version 1 I have simply used a msgbox to display the last modified csv in the folder. Version 2 opens the file and uses filedialog due to OP difficulties with file path from fso.GetFolder.

Add reference to MS Scripting runtime (tool > references ) then

Sub GetLastModifiedCSV()

   'Early binding code. Requires reference to MS Scripting Runtime
    Dim fso As Scripting.FileSystemObject     
    Set fso = New Scripting.FileSystemObject

   'Late binding code. To be used instead of two lines above if "user-defined type not defined" /No reference added. You would uncomment line below.

  'Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject") 

    Dim myFolder As Object

    Set myFolder = fso.GetFolder("C:\Users\User\Desktop\Test")

    Dim currentFile As Object
    Dim maxFileName As String
    Dim maxDate As Date

    For Each currentFile In myFolder.Files

        If fso.GetExtensionName(currentFile) = "csv" Then

            If currentFile.DateLastModified > maxDate Then
                 maxDate = currentFile.DateLastModified
                 maxFileName = currentFile.Name
            End If

        End If

    Next currentFile

   Msgbox maxFileName

End Sub

Additional references:

1) How to get the last modified file in a directory using VBA in Excel 2010

2) Using VBA FileSystemObject, specific file File extension

3) File system object explained

4) msoFileDialogFolderPicker

Version 2 Using FileDialog to get folderpath for GetFolder:

Option Explicit

Public Sub GetLastModifiedCSV()

    Const folderPath As String = "C:\Users\User\Desktop\Test"

   'Early binding code. Requires reference to MS Scripting Runtime
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject

   'Late binding code. To be used instead of two lines above if "user-defined type not defined" /No reference added. You would uncomment line below.

  'Dim fso As Object: Set fso = CreateObject("FileSystemObject")

    Dim myFolder As Object
    Dim currentFile As Object
    Dim maxFileName As String
    Dim maxDate As Date

    With Application.FileDialog(msoFileDialogFolderPicker)

    If .Show Then
      Set myFolder = fso.GetFolder(.SelectedItems(1))  ' & "\" 
    Else
        Exit Sub
    End If

    End With

    For Each currentFile In myFolder.Files

        If fso.GetExtensionName(currentFile) = "csv" Then

            If currentFile.DateLastModified > maxDate Then
                 maxDate = currentFile.DateLastModified
                 maxFileName = currentFile.Name
            End If

        End If

    Next currentFile

    'MsgBox maxFileName

    Workbooks.Open fso.BuildPath(myFolder, maxFileName) 

End Sub
QHarr
  • 83,427
  • 12
  • 54
  • 101
  • What does Compile error "user-defined type not defined" mean? – The Dude MAN Feb 28 '18 at 20:40
  • I'm still getting a path not found error when I run the code. I'm also not sure where I tell the code to pull the file from my Z: drive. I'm sorry for being slow, I'm still learning. Thank you for your time and help QHarr! – The Dude MAN Feb 28 '18 at 22:19
  • that's not a problem. so we have clered the initial error. Now you should have replaced this Const folderPath As String = "C:\Users\User\Desktop\Test" with Const folderPath As String = "yourfolderpath\yourfolder" to get to the folder containing the CSVs you are working with. Are you using a Windows machine btw as process is slightly different for mac. Don't be afraid to ask questions though tomorrow will now be the response timeframe. – QHarr Feb 28 '18 at 22:25
  • Thanks. Take your time. I replaced "yourfolderpath\yourfolder" with "Z:/" At this point the code runs properly but the only thing that happens is an empty message box pops up. – The Dude MAN Feb 28 '18 at 22:56
  • No I'm using Windows on a PC. But I just copy the destination of my folder from the file explorer destination bar. and it gives me Z:\ – The Dude MAN Mar 01 '18 at 18:15
  • You're right my b. At this point I don't get any errors. The macro runs and a blank msg box pops up but no files open. – The Dude MAN Mar 01 '18 at 18:48
  • No, I really appreciate all your time and help trying to figure this out. I'm using the latest version of windows and excel. Version two opens the Windows explorer where I select my Z drive to open. But none of the files show up in the drive. The msg box is still empty. – The Dude MAN Mar 02 '18 at 15:38
  • If I could attach screenshots I would... I feel like we are close to the solution but it's not recognizing .czv files when it looks for files to open. – The Dude MAN Mar 02 '18 at 15:41
  • The longer route is to use the Dir function to produce the files in a loop and check for csv. I am guessing it makes no difference if you put .csv? It should be csv though. Did you try the loop I suggested of putting debug.print currentFile.Name as a line above For Each currentFile In myFolder.Files ....and then looking in the immediate windows (Ctrl & G) to see if any files being processed by fso? – QHarr Mar 02 '18 at 15:51
  • Cool okay so now the message box displays the name of the file that I want to open but it does not open. Any suggestions? – The Dude MAN Mar 02 '18 at 20:21
  • Why does it now display? Have you changed something? I didn't add the code for open sorry as I was just getting you the file! Is it my code as written above that is currently working? If so, I will add the open code. – QHarr Mar 02 '18 at 21:24
  • Hey sorry I was out sick yesterday and I have been playing catchup most of today. I added the open code and now when I try to run it says 'excel cannot find Z:\" Its in the same place as always tho so I don't know why excel cant find it. – The Dude MAN Mar 06 '18 at 18:34
  • Debugging highlights the Workbooks.Open code I just imported – The Dude MAN Mar 06 '18 at 18:36
  • Is this a shared network drive? https://social.technet.microsoft.com/Forums/ie/en-US/db9d5bd8-2d30-432f-95cf-5c11bf95dd18/cant-open-word-or-excel-documents-on-mapped-network-drive-using-office-2013?forum=officeitpro – QHarr Mar 06 '18 at 20:25
  • Yes. Is that a problem? – The Dude MAN Mar 06 '18 at 20:29
  • that is why my code, which is correct, is having problems for you! Mystery likely solved. This issue is discussed in the link i posted but may not be straightforward to resolve. Is this an issue you have an IT department that could look at? You could give them the link I mentioned? – QHarr Mar 06 '18 at 20:31
  • It discussed two things in particular: Allowed Trusted Locations on my network is checked and Deleting and remapping the drive. – QHarr Mar 06 '18 at 20:32
  • My I.T. dept. doesn't know jack so I'm ditching the automatic selection portion of this macro and switching to a manual selection. Where once you run the macro, a popup prompts you to select the file manually. The entire process involves opening a document, preforming simple formatting changes to the data, then saving and renaming the file. I had hopped the create a macro that automated all of this but it doesn't look possible for the macro to select the correct file reliably. – The Dude MAN Mar 07 '18 at 16:50
  • Do you foresee any problems with the code saving the updated file in my shared Z drive? In other words, will the code allow me to save in a shared drive or will it sketch out because of the shared file. – The Dude MAN Mar 07 '18 at 16:53
  • it is difficult for me to say but it could be related to this trusted location point. It might something you can do yourself same as with a drive re-map. If you run the code and select something from your desktop folder or local folder does it work fine? – QHarr Mar 07 '18 at 18:52