Home » excel » excel – copy and paste from one sheet to another with search and loop

excel – copy and paste from one sheet to another with search and loop

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am essentially trying to search from sht1 for a keyword, copy the whole range from sht1 to sht2 and make sure sht2 start pasting from rowp 10. Then the loop should search through sht1 for the same keyword and for sht2 continue looping to rowp 11 until the end of the loop. For sht1 it is ok, but when it is paste onto sht2 the results are not looping but somehow getting the same no. of space as compare to sht1. not sure how to resolve it.
below are my codes. would appreciate some advice =)

Sub shipshore()

Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim row As String
Dim rowp As String

row = 2
rowp = 10


Set wb = ThisWorkbook
Set sht1 = wb.Sheets("datasheet")
Set sht2 = wb.Sheets("Sheet1")

Do Until sht1.Range("G" & CStr(row)) = ""

If sht1.Range("F" & CStr(row)) = "abc" Then
Sheets("datasheet").Range("A" & CStr(row) & ":J" & CStr(row)).Copy

Sheets("Sheet1").Range("A" & CStr(rowp) & ":J" & CStr(rowp)).PasteSpecial _
Paste:=xlPasteValues



End If

row = row + 1
rowp = rowp + 1
Loop

End Sub
How to&Answers:

If I understand correctly your need, you should increment rowp only after a positive match to continue copying after the precedent row of sht2. Try this way:

Sub shipshore()

Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim row As String
Dim rowp As String

row = 2
rowp = 10


Set wb = ThisWorkbook
Set sht1 = wb.Sheets("datasheet")
Set sht2 = wb.Sheets("Sheet1")

Do Until sht1.Range("G" & CStr(row)) = ""

  If sht1.Range("F" & CStr(row)) = "abc" Then
    Sheets("datasheet").Range("A" & CStr(row) & ":J" & CStr(row)).Copy

    Sheets("Sheet1").Range("A" & CStr(rowp) & ":J" & CStr(rowp)).PasteSpecial _
           Paste:=xlPasteValues
    rowp = rowp + 1    
  End If

  row = row + 1

Loop

End Sub