Copy cells to another Worksheet if they do not exist

Asked

Viewed 388 times

0

In the Worksheet "BASE" I enter various customer data (NIF, name, address, telephone, email). I have a Worksheet "DATA" where you have a list of several clients.

I need to create a button on the Worksheet "BASE" that copies the data from the client to the Worksheet "DATA" if it does not exist based on the NIF but if it exists updates the information on the Worksheet "DATA".

I also need to create a button in the Worksheet "BASE" that searches in the WS "DATA" a certain "NIF" and copies the information to the WS "BASE".

I hope you can help me. I don’t have much experience with vba and this will save me a lot of work.

Thank you

1 answer

0

Come on. If I understood correctly, would this NIF be the index of the spreadsheet? In this case the following code should help you:

Sub copiar()

lRow1 = Plan1.Cells(Rows.Count, 1).End(xlUp).Row
lRow2 = Plan2.Cells(Rows.Count, 1).End(xlUp).Row
lCol1 = Plan1.Cells(1, Columns.Count).End(xlToLeft).Column
lCol2 = Plan2.Cells(1, Columns.Count).End(xlToLeft).Column

For i = 2 To lRow1
    x = 0
    For d = 2 To lRow2

        If Plan1.Cells(i, 1).Value = Plan2.Cells(d, 1).Value Then

            For b = 1 To lCol1

                Plan2.Cells(d, b).Value = Plan1.Cells(i, b).Value

            Next b
            x = x + 1
            Exit For

        End If

    Next d

    If x = 0 Then
        lRow2 = lRow2 + 1
        For b = 1 To lCol1

            Plan2.Cells(lRow2, b).Value = Plan1.Cells(i, b).Value

        Next b
    End If


Next i


End Sub

That code will check if what’s on the line i of Plan1 (BASE) exists in Plan2 (DATA) checking if the NIF already exists, if it does not exist it copies and repeats the process to the next line until the completed lines in the Plan1(DICE).

  • At Plan1 (BASE) I only have one line with information. In Plan2 (DATA) I have my total database to which I want to add more "clients" and complete the existing information. So, if there is no NIF add one more line in Plan2 with this information. If there is NIF replace this line with new information.

  • @Mcardoso edited the answer, added the copy of the data for when he finds the NIF in the other table. As for you having only one line, it is not a problem, the code will run while there are filled lines, so you add only one as said, or add N lines and it will run while there are lines to check.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.