Alvaroro84
Board Regular
- Joined
- May 13, 2022
- Messages
- 65
- Office Version
- 2016
- Platform
- Windows
The code seem to capture the file path correctly. However, it is saying that the formula is incorrect Does any one have any suggestion on what is wrong with the code below?
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")
Debug.Print MyPath & LatestFile
ActiveCell.Formula2R1C1 = _
"=XLOOKUP(RC[-3],',[" & MyPath & LatestFile & "]Cos'!C3,'[" & MyPath & LatestFile & "]Cos'!C4,0)"
''ActiveCell.Formula2R1C1 = "=XLOOKUP(RC[-3],'[" & MyPath & LatestFile & "]Cos'!C3,'[" & MyPath & LatestFile & "]Cos'!C4,0)"
Sheets("Sheet1").Range("D2:D" & lastrow).Cells.SpecialCells(xlCellTypeVisible).Formula2 = ActiveCell.Formula2
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
VBA Code:
ActiveCell.Formula2R1C1 = _
"=XLOOKUP(RC[-3],',[" & MyPath & LatestFile & "]Cos'!C3,'[" & MyPath & LatestFile & "]Cos'!C4,0)"