Compare File Date Modified in VBA - vba

So I am writing a code in VBA that opens up all files in a document and copies and pastes the information from each document. The code is set up to open up every document, but itself. My dilemma is that I want the code to open ever document that has been modified after the last day the main file has been modified. Basically I want to compare two dates with one date staying the same and the other changing after every loop (new document every loop). My code is below and any help or suggestion would be much appreciated. Thanks!
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date
Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")
Do While Len(MyFile) > 0
If MyFile = "zmasterfile.xlsm" Then
Exit Sub
If DateReflections < DateMaster Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("B4:N4").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))
MyFile = Dir
Loop
End Sub

You shouldn't be exiting the sub in your if statement. You might consider changing you IF statement to something like below:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date
Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")
Do While Len(MyFile) > 0
DateReflections = FileDateTime(Filepath)
If MyFile <> "zmasterfile.xlsm" and DateReflections > DateMaster Then
Workbooks.Open (Filepath & MyFile)
Range("B4:N4").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))
End If
MyFile = Dir
Loop
End Sub

You just need to reset the DateReflections in your loop, using MyFile to build the file path. See below.
If MyFile = "zmasterfile.xlsm" Then
Exit Sub
DateReflections = FileDateTime(Filepath & "\" & MyFile)
If DateReflections < DateMaster Then
Exit Sub
End If
As an aside, if you'd like to just skip the file and continue processing, rather than exiting the sub entirely, replace your Exit Subs with Continue Do

Related

Excel VBA Paste Error "...isn't the same size..."

NB: I'm brand new to VBA and code in general
I've attempted to make a macro that collates data from multiple workbooks and imports it into a master workbook ('ZMaster').
The following code successfully copies data from the cell C5 in multiple workbooks (from file C:\AutoMelinh) and pastes them in a column in my 'ZMaster' workbook.
The issue is I get the error 'The data you are pasting isn't the same size as your selection. Do you want to paste anyway?'. This comes after every paste, so I have to click 'ok' every single time. The format of the cell that is copied, is merged (between C5 and D5). I think this is the issue however I don't know how to mitigate that in the VBA code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("C5").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Loop
End Sub
EDIT: I was able to solve the issue by using
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then
Exit Sub
End If
Application.DisplayAlerts = False
Workbooks.Open (Filepath & MyFile)
Range("C5").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Application.DisplayAlerts = True
Loop
End Sub
you are getting the warning because you are pasting one cell into 4 cells
this should work without using copy/paste
Sub LoopThroughDirectory()
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
Dim MyFile As String
MyFile = Dir(Filepath)
Dim erow As Range
Dim wb As Workbook
Do While Len(MyFile) > 0
If MyFile = "ZMaster.xlsm" Then Exit Sub
Set wb = Workbooks.Open(Filepath & MyFile)
erow = Workbooks("ZMaster.xlsm").Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
erow.Value = wb.Sheets(1).Range("C5").Value
if isempty(erow) then erow.value = "----------"
wb.Close
MyFile = Dir
Loop
End Sub

Open workbooks in filepath and copy sheet 2 to Masterworkbook

I would like to open all workbooks in a filepath on my hard-drive and then copy table data from sheet 2 to Master workbook with the name of Master.
I found this code and have modified it to suit my needs but I'm stuck.
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMiljö\Prognosverktyg\Sektionsfil\Gruppfiler"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = “master.xlsm” Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Worksheets("FärdigÖnskemål").Range("A4:D4").Select
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("DataÖnskemål").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Loop
End Sub
Any help this friday?
According to your code, it's not clear what Worksheet is the destination sheet (the one you want to paste to), is it Sheet1 or Worksheets("DataÖnskemål").
Anyway, in my code it pastes to Sheet1, let me know if you meant something else.
Code
Option Explicit
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler\"
MyFile = Dir(Filepath)
Do While MyFile <> ""
If Not MyFile Like "master.xlsm" Then
Set wb = Workbooks.Open(Filepath & MyFile)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemål").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
MyFile = Dir()
Loop
End Sub
I would recommend using FileSystemObject instead:
Sub LoopThroughDirectory()
Dim MyFile As File
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Dim FSO As New Scripting.FileSystemObject
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler"
For Each MyFile In FSO.GetFolder(Filepath).Files
If Not MyFile.Name Like "master.xlsm" Then
Debug.Print MyFile.Path
Set wb = Workbooks.Open(MyFile.Path)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemal").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
Next
End Sub
You have to add Microsoft Scripting Runtime reference to your project.
You can read more here

Transferring Data from multiple workbooks

Objective - extracting data from multiple workbooks (5 in total); pasting the data into a new workbook.
Problem/Issue:
1) After running the below VBA code it's able to copy data from all the 5 workbooks but while pasting it's pasting data for only one of them.
2) Pop-up window for Clipboard is full. I've written a code to clear the clipboard but it doesn't seem to function as I still get the pop-up window.
VBA Code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim MyPath As String
MyPath = "Directory path"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If MyFile = "filename.xlsb" Then
End If
Workbooks.Open (MyPath & MyFile)
Range("A3:CP10000").Copy
ActiveWorkbook.Close
'calculating the empty row
erow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
a = ActiveWorkbook.Name
b = ActiveSheet.Name
Worksheets("Raw Data").Paste Range("A2")
Application.CutCopyMode = False ' for clearing clipboard
MyFile = Dir
Loop
End Sub
I tried two other commands below as well, but they seem to just return no data at all.
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow + 1, 1), Cells(erow + 1, 30)) `pasting the data`
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("A2")`pasting the data`
Update.
Here is the current code:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Users\username\Downloads\PROJECTS\Project Name\Input file\"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If InStr(MyFile, "post_level.xlsb") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
ActiveWindow.Zoom = 90
End Sub
Update2.
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Users\username\Downloads\PROJECTS\ProjectNameFolder\SubFolder\MainFolder\Input file"
MyFile = Dir("C:\Users\username\Downloads\PROJECTS\ProjectNameFolder\SubFolder\MainFolder\Input file\*.*")
Do While Len(MyFile) > 0
If InStr(MyFile, ".csv") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
End Sub
I hope I can help... There are multiple errors in your code, and I am not sure if I fixed them the way you'd want.
It would be useful to mention just one main mistake. You cannot have these 2 lines together:
If MyFile = "filename.xlsb" Then
End If
Between these lines you must put every procedure that you want to do IF he If condition is met. In the original case, if there was a file named "filename.xlsb", nothing would have happened, as you immediately closed the code block...
Try something similar to the following code. It worked for me to import data from all the files in the directory C:\Temp\ which have the extension of .xlsb
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim MyPath As String
Dim wb As Workbook
MyPath = "C:\Temp\"
MyFile = Dir(MyPath)
Do While Len(MyFile) > 0
If InStr(MyFile, ".xlsb") > 0 Then
Set wb = Workbooks.Open(MyPath & MyFile)
Range("A3:CP10000").Copy
'calculating the empty row
erow = ThisWorkbook.Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Raw Data").Paste (ThisWorkbook.Worksheets("Raw Data").Range("A" & erow + 2))
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End If
MyFile = Dir
Loop
End Sub

Loop Through Directory VBA to Copy Data With Format

I have few files in a directory or a folder and I want to copy a range (values with format to the current sheet). I have VBA code and I think it is not in order or something is missing in the code. Please help me to fix the issue.
(I have defined named range in each files in the directory. Is it is possible to copy using the named range?)
Copy from directory files given path & from sheet2 & paste it to file "workbook.xlsm" Sheet "sheet1"
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\test"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "workbook.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Sheets("Sheet2").Select
Range("A1:N24").Copy
Workbooks.Open ("Filepath & workbook.xlsm")
If Sheets("Sheet1").Range("A1") = vbNullString Then
Sheets("Sheet1").Range ("A1:N24")
Selection.PasteSpecial Paste:=xlPasteFormats
Selection.PasteSpecial Paste:=xlPasteValues
Else
Selection.Copy Sheets("sheet1").Cells(A1, Columns.Count).End(xlToLeft).Offset(0, 1)
End If
MyFile = Dir
Loop
End Sub
One question remains:
(I have defined named range in each files in the directory. Is it is possible to copy using the named range?)
It's certainly possible. Thus assuming the Defined Name range is "DATA".
Just replace this line:
sourceWbk.Sheets("Sheet2").Range("A1:N24").Copy
with this:
sourceWbk.Sheets("Sheet2").Range("DATA").Copy
Actually, OP mentioned that this Names are generated by another procedure with the address "A1:N24". So in the case that the address is changed then there will be a need to update every other procedure that refers to it, instead by using the Defined Name don't have to worry about it as it will be taking care by design. That why it’s a good practice to use Defined Names.
I'd use this method:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim FilePath As String
Dim colFiles As Collection
Dim vFile As Variant
Dim wrkbkSource As Workbook
Dim wrkbkTarget As Workbook
Dim rngTarget As Range
FilePath = "C:\test\"
MyFile = "workbook.xlsm"
Set colFiles = New Collection
EnumerateFiles FilePath, "*.xlsm", colFiles
Set wrkbkTarget = Workbooks.Open(FilePath & MyFile)
For Each vFile In colFiles
If vFile <> FilePath & MyFile Then
Set wrkbkSource = Workbooks.Open(vFile, False)
wrkbkSource.Worksheets(1).Range("A1:N24").Copy
Set rngTarget = wrkbkTarget.Worksheets("Sheet1").Cells(1, wrkbkTarget.Worksheets("Sheet1").Columns.Count).End(xlToLeft)
rngTarget.PasteSpecial xlPasteFormats
rngTarget.PasteSpecial xlPasteValues
wrkbkSource.Close False
End If
Next vFile
End Sub
This procedure is needed to get all the files in the folder:
Sub EnumerateFiles(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sDirectory & sTemp
sTemp = Dir$
Loop
End Sub
Okay see if it works for you, had to add quite a bit
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim targetWbk As Workbook
Dim sourceWbk As Workbook
Filepath = "C:\test"
MyFile = Dir(Filepath)
Workbooks.Open (Filepath & "\workbook.xlsm")
Set sourceWbk = ActiveWorkbook
Do While Len(MyFile) > 0
If Not MyFile = "workbook.xlsm" And MyFile = "*.xls*" Then
Workbooks.Open (Filepath & MyFile)
Set sourceWbk = ActiveWorkbook
sourceWbk.Sheets("Sheet2").Range("A1:N24").Copy
If targetWbk.Sheets("Sheet1").Range("A1") = vbNullString Then
targetWbk.Sheets("Sheet1").Range("A1:N24").PasteSpecial xlPasteFormulas, xlPasteValues
Else
targetWbk.Sheets("sheet1").Cells(A1, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial xlPasteFormulas, xlPasteValues
End If
MyFile = Dir
End If
Loop
End Sub

PasteSpecial Method of Range Run Error

Sub LoopOtherRevenue()
Dim MyFile As String
Dim FilePath As String
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
ActiveSheet.Range("A1:B14").Copy
Workbooks.Open (FilePath & MyFile)
ActiveWorkbook.Worksheets("A2) Monthly P&L (Source)").Activate
Range("B746:C759").PasteSpecial xlPasteValues
Application.CutCopyMode = False
ActiveWorkbook.Close
MyFile = Dir
Loop
End Sub
Get a paste special error on line Range("B746:C759").PasteSpecial xlPasteValues
The values are being pasted into a combo box. that is where the error is coming from.
For me it seems like the file path is missing a "\"
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other"
...
MyFile = Dir(FilePath)
...
If MyFile = "Book1.xlsm" Then
...
Workbooks.Open (FilePath & MyFile)
Correct:
Workbooks.Open (FilePath & "\" & MyFile)
Did you try debugging? Where does it throw the error?
I can see all sorts of issues because you're using ActiveWorkbook after opening the 2nd workbook. Is ActiveWorkbook still pointing at the one where the code is, or is it actually pointing at the one you just opened?
Create & set an as Workbook variable as assign the one the code is in to one, and the workbook you're opening to the other. That will eliminate all confusion.
Try this:
Sub LoopOtherRevenue()
Dim rgCopy as Range
Dim MyFile As String
Dim FilePath As String
Dim wb as Workbook
FilePath = "destination folder\"
MyFile = Dir(FilePath)
Set rgCopy = ActiveSheet.Range("A1:B14")
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
set wb Workbooks.Open(FilePath & "\" & MyFile)
rgCopy.Copy Destination:=wb.Worksheets("A2) Monthly P&L (Source)").Range("B746")
wb.Close
MyFile = Dir
Loop
End Sub