Im completely new to VBA. I'm trying to write macro what open latest file from folder and copy and past data from specific sheet. I need to copy data from file opened by VBA (latest file from folder) and copy data from one sheet to my current file (Expiry date sheet).
I don't know how to declare open file as workbook from where I want to copy data. Any advice?
Private Sub CommandButton1_Click()
'Declare the variables
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Set Y = Workbooks("TEST")
MyPath = "C:\Users\e9\Desktop\Automatyczne sprawdzanie expiry date\New folder\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", 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
End Sub