Need a VBA macro to search a field and if value found copy the whole row into another worksheet.

I have a worksheet “Sheet1”with one of the colums “EID”. I want to search for a value in this column and if found want to copy and paste the whole row in another worksheet “Sheet2” in a particular line.  Say in line 4, over writing the data if any in line 4 .

I need a macro please.

Top Contributor Asked on May 19, 2017 in Excel: General.
Add Comment
1 Answer(s)

HI,

Here is the required macro to search a field and if value found copy the whole row into another worksheet.

Sub Search_Field_Update_Another_Sheet()
'Variable declaration
Dim lstRow_Sht1 As Integer, lstRow_Sht2 As Integer, iCnt As Integer, jCnt As Integer
Dim Sht1 As Worksheet, Sht2 As Worksheet
Dim srchField As String
Set Sht1 = Sheets("Sheet1")
Set Sht2 = Sheets("Sheet2")
'Find last row in sheet1
lstRow_Sht1 = Sht1.Cells(Sht1.Rows.Count, "A").End(xlUp).Row
'Find last row in sheet2
lstRow_Sht2 = Sht2.Cells(Sht2.Rows.Count, "A").End(xlUp).Row
'Enter search field
srchField = InputBox("Enter Search Field", "Find Field")
'Loop through all rows in sheet1
For iCnt = 2 To lstRow_Sht1
'lets assume EID is available in column A in Sheet1
If Sht1.Range("A" & iCnt) = CInt(srchField) Then
For jCnt = 1 To lstRow_Sht2
'lets assume EID is available in column A in Sheet2
If Sht2.Range("A" & jCnt) = srchField Then
'If field is available then update existing data
Sht1.Rows(iCnt).Copy Destination:=Sht2.Range("A" & jCnt)
Exit Sub
Else
If jCnt = lstRow_Sht2 Then
'If field is not available then add after the last record
Sht1.Rows(iCnt).Copy Destination:=Sht2.Range("A" & jCnt + 1)
Exit Sub
End If
End If
Next
Else
If iCnt = lstRow_Sht1 Then
'If search field is not available in sheet2 then display message
MsgBox "Search Field is not available."
End If
End If
Next
End Sub

 

Hope, It resolves your problem.

Regret the delay in response.

Regards-Valli!

Expert Answered 5 mins ago.
Add Comment
  • Found this useful?

    Please share using the share button above.

    If you found the answer is best answer for your question, Please mark as 'best answer' by clicking on the right tick mark icon at the left side of the answer.

    Found the answer useful and wants to credit the user, then vote the answer (vote up).

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.