Pull Filename From Latest File - excel

I am using the following code (co-opted from someone here) to access the latest generated files from a folder. I use it to open the file and do various bits (example below). But I was wondering if there is a way to pull the filename from the latest file and paste it into a cell in another workbook?
Sub Macro3()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Application.DisplayAlerts = False
MyPath = "C:\Users\XXXX\Desktop\folderXXX"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "XYZ-********-123.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
Range("B2:D97").Copy
ActiveWindow.Close
Windows("New.xlsm").Activate
Range("A2").Select
ActiveSheet.Paste
End Sub
Can it been done with the existing code, is it as simple as adding something to this line Workbooks.Open MyPath & LatestFile instead of .Open?
Appreciate any help or tips even tips to tidy it up in any way. Thanks

You can do something like this:
Sub Macro3()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim wb As WorkBook, wsDest As Worksheet '<<<
Application.DisplayAlerts = False
MyPath = "C:\Users\XXXX\Desktop\folderXXX"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "XYZ-********-123.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
Set wsDest = ThisWorkbook.WorkSheets("Data") '<< for example
Set wb = Workbooks.Open(MyPath & LatestFile)
wb.Sheets(1).Range("B2:D97").Copy wsDest.Range("A2")
wb.Close False '<< don't save
wsDest.Range("A1").Value = LatestFile '<< record the file name
End Sub

Related

VBA from latest file in a folder ("Run-time error 1004")

I used the below code to open the latest file in a folder and Vlookup from it and return the value which is in column I.
I am facing a Run-time error 1004, although everything is correct.
i Set wbname = ActiveWorkbook.Name to catch the open sheet name which I will put the Vlookup formula in and I am choosing the correct range for my formula which is I2, still can't figure out where did I go wrong.
Error Message in the below line:
Range("I2").Formula = _
"=VLOOKUP(A2,[" & MyPath & LatestFile & "]'Sheetname with input data'!A:I,9,False)"
My Code:
Sub PrepareforOutlookMails()
wbname = ActiveWorkbook.Name
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim wb As Workbook
Dim fileLocation As String
Dim fileToOpen As Workbook
MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'first Excel file from the folder
MyFile = Dir(MyPath & "*.xls", vbNormal)
'If no files exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each Excel file in the folder
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
Workbooks(wbname).Activate
Range("I2").Formula = _
"=VLOOKUP(A2,[" & MyPath & LatestFile & "]'Sheetname with input data'!A:I,9,False)"
Like I mentioned VLOOKUP works on closed file as well. There is no need to open the file.
Your [ and ] and ' placement is incorrect. Here is an example (Untested)
If you manualy type the formula, it will look like this
=VLOOKUP(D2,'C:\1.ER\1.Work\19.Etr\Recon\2022\October\[Mail Merge (Updated Sample File) (1).xlsx]Sheetname with input data'!A:I,9,0)
Sub Sample()
Dim MyPath As String
Dim LatestFile As String
MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October\"
LatestFile = "Mail Merge (Updated Sample File) (1).xlsx"
Range("I2").Formula = "=VLOOKUP(A2,'" & _
MyPath & _
"[" & _
LatestFile & _
"]Sheetname with input data'!A:I,9,0)"
End Sub
EDIT
This is how your original code can be written. I have commented the code so you should not have any problem understanding it.
Option Explicit
Sub PrepareforOutlookMails()
Dim wbThis As Workbook
Dim wsThis As Worksheet
Dim MyPath As String
Dim MyFile As String
Dim LMD As Date
Dim LatestFile As String
Dim LatestDate As Date
Set wbThis = ThisWorkbook
'~~> Change this to the relevant sheet
'~~> This is where the formula will be written
Set wsThis = wbThis.Sheets("Sheet1")
'MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October"
MyPath = "C:\Users\routs\Desktop"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'~~> First Excel file from the folder
MyFile = Dir(MyPath & "*.xls*", vbNormal)
'~~> If no files exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each Excel file in the folder
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
wsThis.Range("I2").Formula = "=VLOOKUP('" & wsThis.Name & "'!A2,'" & _
MyPath & _
"[" & _
LatestFile & _
"]Sheetname with input data'!A:I,9,0)"
End Sub
Screenshot

VBA code to automatically import "NEWEST" csv file into specific sheet

I am wanting to write a VBA code to import the newest .csv file from a certain directory into a specific excel sheet. I am currently using a code that works, BUT it opens up in a new workbook and I cannot figure out how to append it to a certain sheet instead. If that makes sense? Also, is there a way to also delete all duplicates within that specific sheet after imported?
The code I am currently using through VBA is below....
Option Explicit
Sub NewestFile()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Users\Documents\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", 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
The issue is that this code opens up in a new workbook instead of importing into a specific sheet.

Open Last File save base on creation date, NOT Last modify

I'm new on VBA, currently, I been seen the way to open a workbook base on creation date, I have found several codes but this open last save workbook or last modify file, sometimes last files are not the workbook I need and I will like to replace from last save file to the creation date.
Below its an example of code, I have found.
Sub NewestFile()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Users\Documents\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", 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

I have code that calls the most recent file in my folder how can I call that file in a Vlookup function

Hello I using a function that calls out the most recent file in my folder. I need to automate a vlookup for the file. I'm having problems properly calling the file out
I already tried calling it by its path but I believe I didn't call it correctly .
Sub oversub()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Users\TAmon1\Desktop\OverSubscription Dash"
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
Dim wb As Workbook
'wbstring = MyPath & LatestFile
Windows("Planning_tool.xlsm").Activate
Range("N2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(C[-13],'Router_level_crosstab.csv'!C1:C11,11,FALSE)"
Range("N2").Select
Selection.AutoFill Destination:=Range("N2:N539")
Range("N2:N539").Select
Range("P2").Select
ActiveCell.FormulaR1C1 = ""
Range("O2").Select
'ActiveSheet.Paste
Range("O2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(C[-14],'Router_level_crosstab.csv'!C1:C11,5,FALSE)"
Range("O2").Select
Selection.AutoFill Destination:=Range("O2:O539")
Range("O2:O539").Select
Range("Q2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(C[-16],'Router_level_crosstab.csv'!C1:C11,9,FALSE)"
Range("Q2").Select
Selection.AutoFill Destination:=Range("Q2:Q539")
Range("Q2:Q539").Select
Currently I am calling the direct file which does work but when I have the a new file I would need to manually change the file name. I need to incorporate the latest file in the Vlookup.

open last modified excel spreadsheet using vba

I have the following code that i have used to open the last modified CSV file, and have literally just changed the path name and extension, but it now doesnt work, would appreciate any pointers on where i am going wrong:
Code i am using:
Sub ReceiptTest()
On Error Resume Next
With Application.FileSearch
.LookIn = "\\K123456\shared\IT Public\ReceiptsETE\Archive\": .Filename = "*.XLS*"
.Execute msoSortByLastModified, msoSortOrderDescending
For FF = 1 To .FoundFiles.Count
If FileDateTime(.FoundFiles(FF)) > LastModDate Then
LastModDate = FileDateTime(.FoundFiles(FF))
lmf = .FoundFiles(FF)
End If
Next
End With
Workbooks.Open (lmf)
End Sub
Thanks
If you're trying to open a CSV, then your filename should be .csv, not xls. Here's how I do it. You need to set a reference to Microsoft Scripting Runtime. It will work even when you upgrade from 2003
Sub OpenCSV()
Dim sFldr As String
Dim fso As Scripting.FileSystemObject
Dim fsoFile As Scripting.File
Dim fsoFldr As Scripting.Folder
Dim dtNew As Date, sNew As String
Const sCSVTYPE As String = "Microsoft Office Excel Comma Separated Values File"
Set fso = New Scripting.FileSystemObject
sFldr = "C:\Documents and Settings\dick\My Documents\QBExport\"
Set fsoFldr = fso.GetFolder(sFldr)
For Each fsoFile In fsoFldr.Files
If fsoFile.DateLastModified > dtNew And fsoFile.Type = sCSVTYPE Then
sNew = fsoFile.Path
dtNew = fsoFile.DateLastModified
End If
Next fsoFile
Workbooks.Open sNew
End Sub
Ok, I got this to work using Conman's code above with a few modification (I made changes to his code and they will be reflected if they get approved). Here is his code with those changes:
Sub GetLatestFile()
Dim strFolder As String
Dim strFile As String
Dim latestFile As String
Dim dtLast As Date
' assign variables
strFolder = "C:\your\file\path\goes\here\" 'the path of the file drop folder (you need the final "\" on the directory
strFile = Dir(strFolder & "\*.xls*", vbNormal) ' Excel Files
' strFile = Dir(strFolder & "\*.csv", vbNormal) ' CSV Files
' strFile = Dir(strFolder & "\*.*", vbNormal) ' Any File
' loop through files to find latest modified date
Do While strFile <> ""
If FileDateTime(strFolder & strFile) > dtLast Then
dtLast = FileDateTime(strFolder & strFile)
latestFile = strFolder & strFile
End If
strFile = Dir
Loop
MsgBox latestFile
End Sub
You can also set strFolder by using a file dialogue and passing it into the above sub. Here is an example:
Sub ChooseFolder()
Dim fd As Office.FileDialog
Dim strFolder As String
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
If .Show Then
strFolder = .SelectedItems(1)
End If
End With
GetLatestFile strFolder
End Sub
Sub GetLatestFile(strFolder As String)
Dim strFile As String
Dim latestFile As String
Dim dtLast As Date
' assign variables
strFolder = strFolder & "\"
strFile = Dir(strFolder & "\*.xls*", vbNormal) ' Excel Files
' strFile = Dir(strFolder & "\*.csv", vbNormal) ' CSV Files
' strFile = Dir(strFolder & "\*.*", vbNormal) ' Any File
' loop through files to find latest modified date
Do While strFile <> ""
If FileDateTime(strFolder & strFile) > dtLast Then
dtLast = FileDateTime(strFolder & strFile)
latestFile = strFolder & strFile
End If
strFile = Dir
Loop
MsgBox latestFile
End Sub
I just tested both chucks of code and they work for me. Let me know if you can't get them to work.
I cannot test your code as I am using Execl 2010 and Application.FileSearch isn't supported.
I use this to find the latest modified file...
Sub GetLatestFile()
Dim strFolder As String
Dim strFile As String
Dim latestFile As String
Dim dtLast As Date
' assign variables
strFolder = "C:\" 'The end of this path must have a \ on it
strFile = Dir(strFolder & "\*.*", vbNormal) ' Any File
' strFile = Dir(strFolder & "\*.xls*", vbNormal) ' Excel Files
' strFile = Dir(strFolder & "\*.csv", vbNormal) ' CSV Files
' loop through files to find latest modified date
Do While strFile <> ""
If FileDateTime(strFolder & strFile) > dtLast Then
dtLast = FileDateTime(strFolder & strFile)
latestFile = strFolder & strFile
End If
strFile = Dir
Loop
MsgBox latestFile
End Sub

Resources