Alvaroro84
Board Regular
- Joined
- May 13, 2022
- Messages
- 65
- Office Version
- 2016
- Platform
- Windows
VBA Code:
Sub Macro1()
Dim lastrow As Long
lastrow = Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeLastCell).Row
Dim MyPath As String
MyPath = "F:\VMWare\"
Dim LatestFile As String
LatestFile = Most_Recently_Modified_ExcelFile_In_This_Folder(MyPath, "xls")
Dim sFormula As String
ActiveSheet.Range("A1").AutoFilter Field:=4, Criteria1:="0"
ActiveSheet.Range("D2:D" & Rows.count).SpecialCells(xlCellTypeVisible).Range("A1").Select
' Create formula string
sFormula = "=XLOOKUP(RC[-3],[" & LatestFile & "]Cos!C3,[" & LatestFile & "]Cos!C4,0)"
' Print formula string to immediate window (Ctrl+G) if window is not visible
Debug.Print sFormula
ActiveCell.FormulaR1C1 = sFormula
Sheets("Sheet1").Range("D2:D" & lastrow).Cells.SpecialCells(xlCellTypeVisible).Formula = ActiveCell.Formula
End Sub
Function Most_Recently_Modified_ExcelFile_In_This_Folder(folderPath As String, fileExtension As String)
fileExtension = Replace(fileExtension, ".", "")
If Right(folderPath, 1) = "\" Then folderPath = Left(folderPath, Len(folderPath))
Dim xFolder, xFile, fileName As String, counter As Integer, latestDate As Date
counter = 0
With CreateObject("Scripting.FileSystemObject")
Set xFolder = .GetFolder(folderPath)
For Each xFile In xFolder.Files
If Mid(xFile.Name, InStrRev(xFile.Name, ".") + 1, 3) = fileExtension Then
If counter = 0 Then
fileName = xFile.Name
latestDate = xFile.DateLastModified
counter = 1
Else
If xFile.DateLastModified > latestDate Then
latestDate = xFile.DateLastModified
fileName = xFile.Name
End If
End If
End If
Next xFile
End With
Most_Recently_Modified_ExcelFile_In_This_Folder = fileName
End Function