open last modified excel spreadsheet using vba - excel

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

Related

i need to find the last saved file in a Folder and move(or copy) it to an other folder, using VBA. Can anybody help me put with that?

I need to look in a specific folder and find the last file saved and move(or copy) to an other folder using VBA.
by finding the file i'm using:
Private Function fFindLastFile()
'Call GetFolder
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim myFolder As Object
Set myFolder = fso.GetFolder("D:\SF\C0T460A220000042\")
'Set myFolder = fso.GetFolder(GetFolder)
Dim myFile As Object
Set myFile = myFolder.Files.Item(myFolder.Files.Count) '<----- this is where i get a debug nr 5, unknown procedure or argument
MsgBox myFile.Name & " was last modified on " & myFile.DateLastModified
End Function
I don not have the name or type of the file that i'm looking for, but i just downloaded it from a known URL.
do you have any ideas what i'm doing wrong?
Last Modified File (FileSystemObject)
Option Explicit
Private Sub CopyLastFile()
Const sFolderPath As String = "D:\SF\C0T460A220000042\"
Const dFolderPath As String = "C:\Test\" ' adjust!
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim fsoFolder As Object: Set fsoFolder = fso.GetFolder(sFolderPath)
Dim fsoFile As Object, fName As String, fDate As Date
For Each fsoFile In fsoFolder.Files
If fsoFile.DateLastModified > fDate Then
fName = fsoFile.Name
fDate = fsoFile.DateLastModified
End If
Next fsoFile
If Len(fName) > 0 Then
fso.CopyFile sFolderPath & fName, dFolderPath, True
'fso.MoveFile sFolderPath & fName, dFolderPath, True
MsgBox "File Name: " & fName & vbLf & "Last modified: " & fDate, _
vbInformation, "Last Modified File"
Else
MsgBox "No file found.", vbExclamation, "Last Modified File"
End If
End Sub

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

Select a previous file in a folder and copy it to a new one

I need to do the following:
Allow the user to select any number of files, in any format, and copy them to a new folder.
Create the destination folder if it doesn't exist. In this case, the folder name should be given by the content of the C2 & C3 cells (Range("C2").Value & Range("C3").Text & "\").
Private Sub CommandButton4_Click()
Dim strDirname As String
Dim strDefpath As String
Dim strPathname As String
Dim strFilename As String
Dim FSO
Dim sFile As FileDialog
Dim sSFolder As String
Dim sDFolder As String
strDirname = Range("C2").Value & Range("C3").Text
MkDir strDefpath & "\" & strDirname
strPathname = strDefpath & "\" & strDirname & "\" & strFilename
Set sFile = Application.FileDialog(msoFileDialogOpen)
sDFolder = strDirname & "\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO = New FileSystemObject
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
If Not .Show Then Exit Sub
Set xFolder = FSO.GetFolder(.SelectedItems(1))
For Each xFile In xFolder.Files
On Error Resume Next
xRow = Application.Match(xFile.Name, Range("A:A"), 0)
On Error GoTo 0
Next
End With
End Sub
I know the error is here...
Set xFolder = FSO.GetFolder(.SelectedItems(1))
...because I'm asking it to get a file, not a folder.
It is not very clear to me what you are trying to do but, if you intend to select a folder, you have to use it
Application.FileDialog (msoFileDialogFolderPicker)
instead of
Application.FileDialog (msoFileDialogFilePicker)
Your posted code shows so little resemblance to what you Q asks for, I've disregarded it.
This code follows the description. You may need to alter certain details to fully match your needs
Sub Demo()
Dim FilePicker As FileDialog
Dim DefaultPath As String
Dim DestinationFolderName As String
Dim SelectedFile As Variant
Dim DestinationFolder As Folder
Dim FSO As FileSystemObject
DefaultPath = "C:\Data" ' <~~ update to suit, or get it from somewhere else
' Validate Default Path
If Right$(DefaultPath, 1) <> Application.PathSeparator Then
DefaultPath = DefaultPath & Application.PathSeparator
End If
If Not FSO.FolderExists(DefaultPath) Then Exit Sub
' Get Destination Folder, add trailing \ if required
DestinationFolderName = Range("C2").Value & Range("C3").Value
If Right$(DestinationFolderName, 1) <> Application.PathSeparator Then
DestinationFolderName = DestinationFolderName & Application.PathSeparator
End If
Set FSO = New FileSystemObject
' Get reference to Destination folder, create it if required
If FSO.FolderExists(DefaultPath & DestinationFolderName) Then
Set DestinationFolder = FSO.GetFolder(DefaultPath & DestinationFolderName)
Else
Set DestinationFolder = FSO.CreateFolder(DefaultPath & DestinationFolderName)
End If
' File Selection Dialog
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)
With FilePicker
.AllowMultiSelect = True ' allow user to select multiple files
.InitialFileName = DefaultPath ' set initial folder for dialog
If .Show = False Then Exit Sub ' check if user cancels
For Each SelectedFile In .SelectedItems ' loop over selected files
If SelectedFile Like DefaultPath & "*" Then 'Optional: disallow browsing higher than default folder
FSO.CopyFile SelectedFile, DefaultPath & DestinationFolderName, True ' Copy file, overwrite is it exists
End If
Next
End With
End Sub

Pull Filename From Latest File

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

Excel Macro to convert xlsx to xls

i have bunch of files in folder all of them are in xlsx format, I need to convert them to xls format. This is going to be done on daily bases.
I need a macro which will loop around the folder and convert the file to xls from xlsx with out changing file name.?
Here is the macro I am using to loop
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "C:\Users\myfolder1\Desktop\myfolder\Macro\"
Filename = Dir(Pathname & "*.xls")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
What you are missing is that instead of calling wb.Close SaveChanges=True to save the file in another format, you need to call wb.SaveAs with the new file format and name.
You said you want to convert them without changing the file name, but I suspect you really meant you want to save them with the same base file name, but with the .xls extension. So if the workbook is named book1.xlsx, you want to save it as book1.xls. To calculate the new name you can do a simple Replace() on the old name replacing the .xlsx extension with .xls.
You can also disable the compatibility checker by setting wb.CheckCompatibility, and suppress alerts and messages by setting Application.DisplayAlerts.
Sub ProcessFiles()
Dim Filename, Pathname, saveFileName As String
Dim wb As Workbook
Dim initialDisplayAlerts As Boolean
Pathname = "<insert_path_here>" ' Needs to have a trailing \
Filename = Dir(Pathname & "*.xlsx")
initialDisplayAlerts = Application.DisplayAlerts
Application.DisplayAlerts = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=Pathname & Filename, _
UpdateLinks:=False)
wb.CheckCompatibility = False
saveFileName = Replace(Filename, ".xlsx", ".xls")
wb.SaveAs Filename:=Pathname & saveFileName, _
FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir()
Loop
Application.DisplayAlerts = initialDisplayAlerts
End Sub
Sub SaveAllAsXLSX()
Dim strFilename As String
Dim strDocName As String
Dim strPath As String
Dim wbk As Workbook
Dim fDialog As FileDialog
Dim intPos As Integer
Dim strPassword As String
Dim strWritePassword As String
Dim varA As String
Dim varB As String
Dim colFiles As New Collection
Dim vFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Select folder and click OK"
.AllowMultiSelect = True
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "Cancelled By User", , "List Folder Contents"
Exit Sub
End If
strPath = fDialog.SelectedItems.Item(1)
If Right(strPath, 1) <> "\" Then strPath = strPath + "\"
End With
If Left(strPath, 1) = Chr(34) Then
strPath = Mid(strPath, 2, Len(strPath) - 2)
End If
Set obj = CreateObject("Scripting.FileSystemObject")
RecursiveDir colFiles, strPath, "*.xls", True
For Each vFile In colFiles
Debug.Print vFile
strFilename = vFile
varA = Right(strFilename, 3)
If (varA = "xls" Or varA = "XLS") Then
Set wbk = Workbooks.Open(Filename:=strFilename)
If wbk.HasVBProject Then
wbk.SaveAs Filename:=strFilename & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Else
wbk.SaveAs Filename:=strFilename & "x", FileFormat:=xlOpenXMLWorkbook
End If
wbk.Close SaveChanges:=False
obj.DeleteFile (strFilename)
End If
Next vFile
End Sub
Public Function RecursiveDir(colFiles As Collection, _
strFolder As String, _
strFileSpec As String, _
bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function

Resources