Hi everyone,
I've been trying to create an Active X button to open a file based on the latest date on the filename and copy (the content) from its worksheet to my current workbook.
Inspiration drew from:
https://www.mrexcel.com/forum/excel...el-file-based-latest-date-found-filename.html
But Excel keeps crashing on every other run.
Could someone please check if the code is properly written?
Thank you so much in advance.
I've been trying to create an Active X button to open a file based on the latest date on the filename and copy (the content) from its worksheet to my current workbook.
Inspiration drew from:
https://www.mrexcel.com/forum/excel...el-file-based-latest-date-found-filename.html
But Excel keeps crashing on every other run.
Could someone please check if the code is properly written?
Thank you so much in advance.
Code:
Private Sub CommandButton1_Click()
Dim dtTestDate As Date
Dim sStartWB As String
Dim x As Workbook
Const sPath As String = "C:\Folder\"
Const dtEarliest = #1/1/2018#
dtTestDate = Date
sStartWB = ActiveWorkbook.Name
While ActiveWorkbook.Name = sStartWB And dtTestDate >= dtEarliest
On Error Resume Next
Set x = Workbooks.Open(sPath & "Record - " & Format(dtTestDate, "YYYY-MM") & ".xlsx")
dtTestDate = dtTestDate - 1
On Error GoTo 0
Wend
If ActiveWorkbook.Name = sStartWB Then MsgBox "Earlier file not found."
x.Sheets("Layout").Range("A1:B100").Copy
ThisWorkbook.Sheets("Sheet1").Range("A1:B100").PasteSpecial
'Close x:
x.Close
End Sub