I want to Copy all file names starting with "BRQ" in Folder "C:\Purchases New and Used" where the month and year in the file name matches the month and year in Cell I1 on sheet "Macro" and to paste these in I5 onwards on sheet "Macro"
It would be appreciated if someone could amend my code
It would be appreciated if someone could amend my code
Code:
Sub CopyFileNames()
' Declare variables
Dim folderPath As String
Dim fileName As String
Dim targetSheet As Worksheet
Dim currentCell As Range
Dim pasteRange As Range
Dim filesFound As Boolean
' Set the folder path
folderPath = "C:\Purchases New and Used\"
' Set the target sheet
Set targetSheet = ThisWorkbook.Sheets("Macro")
' Set the current cell with the month and year (assuming it's a date)
Set currentCell = targetSheet.Range("I1")
' Find the next available cell in column I after I4
Set pasteRange = targetSheet.Range("I5")
' Loop through files in the folder
fileName = Dir(folderPath & "BRQ*.xlsm")
Do While fileName <> ""
' Extract the date from the file name
Dim fileDate As Date
Dim fileNameParts() As String
fileNameParts = Split(fileName, " ")
' Check if the file name has the expected number of parts
If UBound(fileNameParts) >= 7 Then
' Try to convert the last two parts to a date
If IsDate(fileNameParts(UBound(fileNameParts) - 2) & " " & fileNameParts(UBound(fileNameParts) - 1) & " " & fileNameParts(UBound(fileNameParts))) Then
fileDate = CDate(fileNameParts(UBound(fileNameParts) - 2) & " " & fileNameParts(UBound(fileNameParts) - 1) & " " & fileNameParts(UBound(fileNameParts)))
' Compare the extracted date with the date in Cell I1
If Format(fileDate, "mm-yyyy") = Format(currentCell.Value, "mm-yyyy") Then
' Paste the file name in the next available cell in column I
pasteRange.Value = fileName
filesFound = True
' Move to the next available cell
Set pasteRange = pasteRange.Offset(1, 0)
End If
End If
End If
' Get the next file in the folder
fileName = Dir
Loop
' Display a message if no matching files were found
If Not filesFound Then
MsgBox "No matching files found in the specified folder.", vbInformation
End If
End Sub [code]