I got 35 files and a master one. In the files , Sheet1, column D has the values 480 and 0. How can i copy the last row ( from all the 35 files ) that has 480 in column D in the master file Sheet3 ? Until now i have used the code for copy the last row but i can't make it to search the column D for value then copy. I really want to run the macro from the master not from the many files (now actually a made a macro to open all the files and run macro cop to copy the last rows but now i must copy only the last row that has 480 value in column D ).Thank you.
Sub cop()
Dim lastS1Row As Long
Dim nextS2Row As Long
Dim lastCol As Long
Dim s1Sheet As Worksheet, s2Sheet As Worksheet
Dim source As String
Dim target As String
Dim path As String
Dim DestLast As Long
source = "Sheet1"
path = "C:\Users\me\Desktop\2.xlsx"
target = "Sheet3"
Application.EnableCancelKey = xlDisabled
Set s1Sheet = ThisWorkbook.Sheets(source)
Set s2Sheet = Workbooks.Open(path).Sheets(target)
lastS1Row = s1Sheet.Range("A" & Rows.Count).End(xlUp).Row
nextS2Row = s2Sheet.Range("A" & Rows.Count).End(xlUp).Row + 1
lastCol = s1Sheet.Cells(1, Columns.Count).End(xlToLeft).Column
For lCol = 1 To lastCol
s2Sheet.Cells(nextS2Row, lCol) = s1Sheet.Cells(lastS1Row, lCol)
Next lCol
s2Sheet.Activate
ActiveWorkbook.Close SaveChanges:=True
s1Sheet.Activate
End Sub
Try this. I'm assuming the 480 is a number and not a string. I added an If-Then to check if last row, column D is equal to 480.
Sub cop()
Dim lastS1Row As Long
Dim nextS2Row As Long
Dim lastCol As Long
Dim s1Sheet As Worksheet, s2Sheet As Worksheet
Dim source As String
Dim target As String
Dim path As String
Dim DestLast As Long
source = "Sheet1"
path = "C:\Users\me\Desktop\2.xlsx"
target = "Sheet3"
Application.EnableCancelKey = xlDisabled
Set s1Sheet = ThisWorkbook.Sheets(source)
Set s2Sheet = Workbooks.Open(path).Sheets(target)
lastS1Row = s1Sheet.Range("A" & Rows.Count).End(xlUp).row
nextS2Row = s2Sheet.Range("A" & Rows.Count).End(xlUp).row + 1
lastCol = s1Sheet.Cells(1, Columns.Count).End(xlToLeft).Column
If (s1Sheet.Cells(lastS1Row, 4).Value = 480) Then ' This is where you check the last row, column D.
For lCol = 1 To lastCol
s2Sheet.Cells(nextS2Row, lCol) = s1Sheet.Cells(lastS1Row, lCol)
Next lCol
End If
s2Sheet.Activate
ActiveWorkbook.Close SaveChanges:=True
s1Sheet.Activate
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.