Code below - copy the last 2 rows data of each workbook files in a folder then paste it all to Master workbook.
Problem 1 - can someone help on how get the codes below copy only the last row of each workbook.
Problem 2 - instead of copying from Col A to last Column of Data, I want to copy only specific columns e.g. Columns A to F, J and M.
Appreciate any help thanks.
Problem 1 - can someone help on how get the codes below copy only the last row of each workbook.
Problem 2 - instead of copying from Col A to last Column of Data, I want to copy only specific columns e.g. Columns A to F, J and M.
Appreciate any help thanks.
VBA Code:
Option Explicit
Sub OpenEachFiles_CopyLastRow_PasteToMaster()
Dim fso, fldr, fName As Object, Cnt, Cnt2, Cnt3, Cnt4, lRow, lCol As Long
Dim ws As Worksheet, rngArray() As Variant, rng As Range
On Error GoTo Errorfix
Cnt2 = 1 'dimension array
Cnt3 = 0 'array positions
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.GetFolder("C:\Users\Tope\Desktop\Data")
For Each fName In fldr.files
If fName.Name Like "*.xls*" Then
Workbooks.Open Filename:=fName
For Each ws In Workbooks(fName.Name).Sheets
If LCase(ws.Name) = LCase("Data") Then
With Sheets("Data")
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(lRow, .Columns.Count).End(xlToLeft).Column
End With
Cnt2 = Cnt2 + 1
ReDim Preserve rngArray(Cnt2)
With Workbooks(fName.Name).Sheets(ws.Name)
Set rng = .Range(.Cells(lRow - 1, 1), .Cells(lRow, lCol))
End With
rngArray(Cnt3) = rng
Cnt3 = Cnt3 + 1
End If
Next ws
Workbooks(fName.Name).Close SaveChanges:=False
End If
Next fName
Cnt = 2
For Cnt4 = 0 To Cnt3 - 1
With ThisWorkbook.Sheets("Master")
.Range(.Cells(Cnt, "A"), .Cells(Cnt + 1, lCol)) = rngArray(Cnt4)
End With
Cnt = Cnt + 2
Next Cnt4
Errorfix:
If Err.Number <> 0 Then
On Error GoTo 0
MsgBox "Error"
End If
Set fldr = Nothing
Set fso = Nothing
End Sub