[Solved] Copy data base on cells value

bigme

Member
good day friends,
i have a task and i have no idea how to solve it.
task :
Note : column D (ID No.) as the key
first entry data will be store in 2nd rows below headers and it will reserve 12 rows down, so when i entry new data it will check the ID No. if it is match data copied to the next rows, but if not, it will copied in the 13rd rows and like the first data it will reserve 12 rows again, continue like that for every new data with no match ID No. but if match it will copied to the next rows.

kindly help me with this task, thank you.

regards,
bigMe
 

Attachments

Hello bigme,

Thanks for sharing your problem with us. I understand that you want to create a data entry form that follows a specific format.

We can create a UserForm to solve your problem. For that, go to the Developer tab and select the Visual Basic option (or, use the keyboard shortcut Alt + F11).
BL3vAc3Ct3jUw4gr1wUH5ejZodMrYzkvKPBBxDkIlm6e3gSVOOCmDPFLnGHi0lLg4R4A4f5EY4BQJJZYbcWPFGW_z2tfyUQb2QRw2FR7j6cyV9RxpWRgp9mDNp-zUPmJiAblTNf98qkhgIKFEDGN4Lg

In the Visual Basic Editor, from the Insert tab, click on the UserForm option.

2Qabpg707Sw0PTR5oYR49htzKQwWXNzo9jbWbiaKzCXXTD-BHCV4akPqLLwnBKZXJ9yEgwEGh8XHEi2YZb3PHIpo3uoQzO3WxSxtNZ6inNqFDprKyM171lnABuuC8VY4QFjHCYNHqZ5kA2we7XWF1hc

Enter 4 Label from the ToolBox and change their Caption, Font, BackColor, and other properties you require.

ql7L5sSQI5jbUr0ZW0nOBQCjinfl7o5FsmJAW1qtRdYSdqaPIJfppWebdd6d2f4xc3DL6ol7oL_nOLxHZ9N_9JOGE4NkCTcd3qlQKYBL8FXaIk_Y50QBYujY1TW3GjM6MAD8LrhtcF-sLzhuq0OROog
Afterward, enter 4 TextBox and 1 CommandButton. Change the Caption, Font, BackColor, and other required properties of the CommandButton.​

htBxPcvKGVvFmbscf9maTMaspjYC-sZoDlS2uqnDN-50Br9R4Y46YfVopwkzblDAGwHi4JkvGffLWP4442nh6LdiDgpnR-sc163SlUTeezIcY1wWBPNY_B2gijEVcRSQc-z8cH6sOmigxUrJ840bdak

Now, double-click on the CommandButton.

xuEt-gzGGJYG3EP22ykC_6SumdPwp7kNaXG_odgdITsRU5Nm_bGESMNvsQZc3PeQ50fb-McBJ9DjoRni5nESTgin6SJCp_oF1rqcAPQo9zecBup0MNdVK1Hz06lDsMWNgRhdOS1L9KrBMLRC0vxCyWQ

Enter the following VBA Code.
Code:
Private Sub CommandButton1_Click()
    Dim ufID, ufNm, ufAdrs, ufCt As String
    Dim ufArr() As Variant
    
    ufID = UserForm1.TextBox1.Value
    ufNm = UserForm1.TextBox2.Value
    ufAdrs = UserForm1.TextBox3.Value
    ufCt = UserForm1.TextBox4.Value
    
    If ufID = "" Or ufNm = "" Or ufAdrs = "" Or ufCt = "" Then
        MsgBox "Please fill all the fields before submitting."
        Exit Sub
    End If
    
    ufArr = Array(ufNm, ufAdrs, ufCt, ufID)
    
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Database")
    
    Dim lastRow, i, j, rowMatch As Integer
    Dim matchID As Boolean
    
    rowMatch = 2
    matchID = False
    lastRow = ws.Cells(Rows.Count, 4).End(xlUp).Row
    
    For i = 2 To lastRow + 1
        If ws.Cells(i, 4).Value = ufID Then
            matchID = True
            rowMatch = i
            Exit For
        End If
    Next i
    
    If lastRow = 1 And matchID = False Then
        For j = 1 To 4
            ws.Cells(2, j).Value = ufArr(j - 1)
        Next j
    End If
    
    If lastRow <> 1 And matchID = False Then
        i = lastRow + 11
        For j = 1 To 4
            ws.Cells(i, j).Value = ufArr(j - 1)
        Next j
    End If
    
    If matchID = True Then
        For i = rowMatch To rowMatch + 11
            If ws.Cells(i, 1).Value = "" Then
                For j = 1 To 4
                    ws.Cells(i, j).Value = ufArr(j - 1)
                Next j
                Exit For
            End If
        Next i
    End If
    
    UserForm1.TextBox1.Value = ""
    UserForm1.TextBox2.Value = ""
    UserForm1.TextBox3.Value = ""
    UserForm1.TextBox4.Value = ""
    UserForm1.Hide
    
End Sub
After that, return to the Excel Window and create a Sheet titled “Data Entry Sheet”. Go to the Developer tab >> click on the Insert dropdown menu >> select CommandButton from the ActiveX Controls option.
PTohNHVCQlWByodct1eXvApVHcBKdjR6itaX2TSMkSnjQQh3pQZcWKFmLl_njGi30I5IUgOKEP_hCbTzeHyMxUiGgxzMHfRqL6zTz7oXTno695j-6nMnAq2SizCYJFQ4iqOzfUEbe-FWyaGYadvZ7ZY

Drag your mouse pointer over the sheet to draw the CommandButton. Right-click over the CommandButton and select Properties.

KKHaj-l_rDgPJBWZLpyXz0LyOL-RssgaOWApTtsSYbZfVgLCOX-FH43WgIs3RxjcMTDNvm95_JPElfb4yRv29-fPnIP0oS3D2RUOpN0ZWNvEpNczcpI-G0hfOyIVE_UJBcb-sbf3TT-a5PwsmR0xUoo

Change the Caption and close the Properties window.
f6rm0NhMTWU8HLD-X71bvQvQpRKZ52xwxve0Zxv2i_kqFozgrpv27piKTKSsvwzZTCnmagjisYJQBongJzEkaMBOZS6yPnwmdnkTw0v8VWt4ZULJqbpkouYigscn_Ap-Bs9QkgQc-UYHjBST2s0yGGU

Right-click on the CommandButton again and select the View Code option.

bXsR_VbUcLiPIEpGESdxXJ_Xur28v4l9XKi5o9Cuv9ltmJpCdnJftcWE2Fyt0WmP5sSlnyCmanRdEZ9o3p1LQMIsQJDq0Z2zUEddXy8IJgfZWtMEAQukY49wouC23FeZMhkBJ3sS5z8LWkqGbX_wzDk

Enter the following VBA Code.
Code:
Private Sub CommandButton1_Click()
    UserForm1.Show
End Sub
Now, close the workbook and re-open it. Go to the Data Entry Sheet and click on the CommandButton. A UserForm will appear. Enter the required data in all the text boxes and click on the Submit button.
4ww3zxgCtXmdSWbPkhw96UAGUmKzPp4qoZ01q0Ml0TGjCKTK4kVzBuq9LZN_V_lENKA3CNYMjg-Md0bXuU9abNtlmp2u2bEYmweteVZCPaNFudNSQesEDCgn5sDA9vl8h2lhyzoYSHeTjUuTbRi7reA

Repeat this process for remaining data or entering new data. The Database looks like the following after entering some of the data.

oYTFaR8hYsT0r4eZVll8BxIlx29ee_mok9nRjhPvd-Fh0TxOitTptqsQ0FMMDtA2nofLeWORBRhZAgvb0fmfQkC0b_bO5DdNbt_Lq2C9vax6bCeFvATHSBURz17By0DGAO5WvXGOmRq_8Wf1cDHfcls

I hope this solution resolves your problem. Let us know your feedback. The workbook used for solving your problem is attached below.

Regards,
Seemanto Saha
ExcelDemy
 

Attachments

dear Seemanto,
a huge thank you for your help, if you please, can you explain the steps of the existing code? so I can understand more. thank you.

regards,
bigMe
 
Hello bigme,
Thanks for sharing your feedback with us. I understand that you want a breakdown of the given code. The VBA Code used is a Click event for a CommandButton on a UserForm. Here is a block-by-block breakdown of the code.​
Code:
Dim ufID, ufNm, ufAdrs, ufCt As String
Dim ufArr() As Variant
Here, I have declared 4 string variables ufID, ufNm, ufAdrs, and ufCt to take input ID No., Name, Address, and City respectively from the 4 TextBoxes in the UserFrom. I have also declared a variant type array ufArr that can hold a list of variables of any data type.​
Code:
ufID = UserForm1.TextBox1.Value
ufNm = UserForm1.TextBox2.Value
ufAdrs = UserForm1.TextBox3.Value
ufCt = UserForm1.TextBox4.Value
This part of the code assigns the values of TextBox1, TextBox2, TextBox3, and TextBox4 to the variables ufID, ufNm, ufAdrs, and ufCt respectively.​
Code:
If ufID = "" Or ufNm = "" Or ufAdrs = "" Or ufCt = "" Then
    MsgBox "Please fill all the fields before submitting."
    Exit Sub
End If
This part of the code checks if any of the four input fields is empty. If any of them is empty, it displays a message box with a warning and exits the sub (i.e. the code stops execution).
Code:
ufArr = Array(ufNm, ufAdrs, ufCt, ufID)
The values of the variables ufNm, ufAdrs, ufCt, and ufID are stored in the array ufArr in the given order.
Code:
Set wb = ThisWorkbook
Set ws = wb.Sheets("Database")
Here, two objects wb and ws are set. The variable wb refers to the workbook containing this VBA code and ws refers to the sheet titled “Database” in the current workbook.​
Code:
Dim lastRow, i, j, rowMatch As Integer
Dim matchID As Boolean
Here, 4 integer variables and 1 boolean variable is declared.
Code:
rowMatch = 2
matchID = False
lastRow = ws.Cells(Rows.Count, 4).End(xlUp).Row
The integer variable rowMatch is set to the first-row value 2 (excluding the row of column headers) and the boolean variable matchID is set to False. The last row in Column 4 of the ws (i.e. Database) worksheet is determined using the End(xlUp) method and assigned to the lastRow variable.​
Code:
For i = 2 To lastRow + 1
    If ws.Cells(i, 4).Value = ufID Then
        matchID = True
        rowMatch = i
        Exit For
    End If
Next i
This block iterates through Column 4 (starting from Row 2 to lastRow + 1) of the ws worksheet using a For loop. If a match for the ufID variable is found in any cell of Column 4, then the matchID variable is set to True, the rowMatch variable is assigned the row number where the match was found and For loop is terminated.​
Code:
If lastRow = 1 And matchID = False Then
    For j = 1 To 4
        ws.Cells(2, j).Value = ufArr(j - 1)
    Next j
End If
If the lastRow variable is equal to 1 and the matchID value is False, then the database doesn't contain any data (except the column headers) currently. Therefore, the data from the UserForm (stored in the ufArr array) is updated in cells of Row 2.​
Code:
If lastRow <> 1 And matchID = False Then
    i = lastRow + 11
    For j = 1 To 4
        ws.Cells(i, j).Value = ufArr(j - 1)
    Next j
End If
If the lastRow variable is not equal to 1 and the matchID value is False, then the ID No. of the data from the UserForm is not in the database. Hence, the next available row after the last row (with a reserve of 12 rows down) is updated with user input from the data entry form.​
Code:
If matchID = True Then
    For i = rowMatch To rowMatch + 11
        If ws.Cells(i, 1).Value = "" Then
            For j = 1 To 4
                ws.Cells(i, j).Value = ufArr(j - 1)
            Next j
            Exit For
        End If
    Next i
End If
If the matchID variable is True, then the ID No. of the data from the UserForm is present in the database. Hence, the code iterates through 12 rows from where the match was found for the user-given ID No. and updates the first empty row with the user input from the data entry form.​
Code:
UserForm1.TextBox1.Value = ""
UserForm1.TextBox2.Value = ""
UserForm1.TextBox3.Value = ""
UserForm1.TextBox4.Value = ""
UserForm1.Hide
Finally, we clear the TextBoxes in the UserForm for the next data entry and hide the UserForm.

We also used the following code for the ActiveX Controls CommandButton.
Code:
Private Sub CommandButton1_Click()
    UserForm1.Show
End Sub
This code represents a Click event. Whenever we click on the Command Button in the Data Entry Sheet, the Data Entry UserForm will appear.

Hopefully, these breakdowns of the VBA code segments will help you understand more about the process of entering data. Let us know your feedback.

If you wish to learn more about how to create a UserForm, insert elements from ToolBox, and change various properties of these elements, navigate through the following article.​

Regards,
Seemanto Saha
ExcelDemy
 
dear Seemanto,
i have a little problem regarding to the array
Code:
ufArr = Array(ufNm, ufAdrs, ufCt, ufID)
The values of the variables ufNm, ufAdrs, ufCt, and ufID are stored in the array ufArr in the given order.

since the sample i given was column A,B,C,D what if i insert new column that cause the ufNm, ufAdrs, ufCt, and ufID in array order change (ex. ufNm, xxx, ufAdrs, xxx, ufCt, xxx, ufID ; xxx is inserted column) , is the code need any correction?, kindly explain please, thank you

regards,
bigMe
 
Last edited:
Hello bigme,
Thanks for sharing your feedback with us. The VBA code provided in the previous replies was based on the sample dataset provided. As the sample dataset contained Name, Address, City, and ID No. in Columns A, B, C, and D respectively, the ufNm, udAdrs, ufCt, and ufID variables were assigned to the ufArr array in that particular order.
However, as you may want to add more variables to the ufArr array, we can make the VBA code more dynamic. Let’s assume you want to add the Age and Profession as well for each user and the modified dataset looks like the following.​
30GnO3ubkeWCKNRysC7i1cejix4iib5_NjLkWy_zy_tfnAdRX2wkvCoJ8haHC31P2vjcby3uwaphcLBHOCiFxTv8YRCc0nh2q3ZXA3zBXogyubrlTwBYHTtT-zn1cVeiiB0cjWfnAcSUqHDLO7qUmgg
To enter the Age and Profession data, we have taken two more TextBoxes in the UserForm.
EH8HomCCy03yuPe2FTcDNGVwnQTylecO7L1xD35l44YgIJj39dWckXpwQqq-2r2NH4qYkGBnw9Chdw3oDX5WUz4MO5ORSSDcQI2JBvhsCh3YlMhzliQDRb3P24wxu1zG-vN6tc1gdmBBvPlW7_7i_1Q
We must assign variables to the ufArr array according to the sequence of the fields (i.e. Names, Age, Address, etc.) in the Database worksheet. If any field is the same for all the data entered, instead of a TextBox, we can set it through a variable and assign it to the ufArr array.

Since the ID No. values can be in any column depending on the number of fields you require and the sequence of the fields in the Database worksheet, we have taken a variable idColumn to update the entered data. According to the current location of ID No. field (Column F), I have set the value of the idColumn variable to 6. You may change it according to your requirement.

Since the total required number of fields may vary, instead of using fixed values 1 To 4, I have used the LBound and UBound functions.
The modified VBA Code is given below.​
Code:
Private Sub CommandButton1_Click()
    Dim ufID, ufNm, ufAdrs, ufCt, ufProf As String
    Dim ufAge As Integer
    Dim ufArr() As Variant
   
    ufID = UserForm1.TextBox1.Value
    ufNm = UserForm1.TextBox2.Value
    ufAdrs = UserForm1.TextBox3.Value
    ufCt = UserForm1.TextBox4.Value
    ufAge = Int(UserForm1.TextBox5.Value)
    ufProf = UserForm1.TextBox6.Value
   
    If ufID = "" Or ufNm = "" Or ufAdrs = "" Or ufCt = "" Or ufAge < 0 Or ufProf = "" Then
        MsgBox "Please fill all the fields before submitting."
        Exit Sub
    End If
   
    ufArr = Array(ufNm, ufAge, ufAdrs, ufCt, ufProf, ufID)
   
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Database")
   
    Dim lastRow, i, j, rowMatch As Integer
    Dim matchID As Boolean
    Dim idColumn As Integer
   
    idColumn = 6
    rowMatch = 2
    matchID = False
    lastRow = ws.Cells(Rows.Count, idColumn).End(xlUp).Row
   
    For i = 2 To lastRow + 1
        If ws.Cells(i, idColumn).Value = ufID Then
            matchID = True
            rowMatch = i
            Exit For
        End If
    Next i
   
    If lastRow = 1 And matchID = False Then
        For j = LBound(ufArr) To UBound(ufArr)
            ws.Cells(2, j + 1).Value = ufArr(j)
        Next j
    End If
   
If lastRow <> 1 And matchID = False Then
    i = lastRow + 11
    For j = LBound(ufArr) To UBound(ufArr)
        ws.Cells(i, j + 1).Value = ufArr(j)
    Next j
End If
   
If matchID = True Then
    For i = rowMatch To rowMatch + 11
        If ws.Cells(i, 1).Value = "" Then
            For j = LBound(ufArr) To UBound(ufArr)
                ws.Cells(i, j + 1).Value = ufArr(j)
            Next j
            Exit For
        End If
    Next i
End If
   
    UserForm1.TextBox1.Value = ""
    UserForm1.TextBox2.Value = ""
    UserForm1.TextBox3.Value = ""
    UserForm1.TextBox4.Value = ""
    UserForm1.TextBox5.Value = ""
    UserForm1.TextBox6.Value = ""
    UserForm1.Hide
   
End Sub
After entering some data, the Database looks like the following after entering some of the data.
A7KtEQdPpQztTurBXCzB0JydaqVdzRX04j0H7CfacWQOOI05mhzM4qhvm4A6MAhr-dPTzWJ7gf5-WWMnxKHYFXuXvVyRX_XNfJ5Ix4G5BSPuZW1Bk7Hu8zdek6X55hHd_craUV1jCm7xNIZvyem4iSY
Hopefully, this solution will resolve your problem. Let us know your feedback. The workbook used for solving this problem is attached below.

Regards,
Seemanto Saha
Exceldemy
 

Attachments

Dear Seemanto,
thank you for your enlightenment, i try this new code but i get error every time i try to update the same ID (please see my attachment), but in the sample you gave there is no error, it works fine, it's driving me crazy to find the problem, please kindly help me, thank you.

regard,
bigMe

original code.JPGss.JPGss1.JPG
 
Last edited:
Dear bigme,
the Application-defined or object-defined error is very common in Excel. It usually occurs when an object (the ws worksheet for example) is not defined properly or parameters related to an object (the i or j variables for example) are invalid.
Although it is not possible to surely say what went wrong in your modified code without seeing the entire code, I can suggest some fixes to check what is actually wrong in your modified code.

>>If you can update data with new IDs, then the ws worksheet and the j variable (header array indices in your code) are defined properly. Else, there is a problem defining the ws worksheet or j variable.

>>If data with new IDs are updated properly and updating data with existing IDs is returning errors, then there must be problems with i variable. As the value of i depends on the rm variable (rowMatch in my code) we can put a MsgBox to check the value of rm. In your code, you will find a block similar to the following:​
1690782699933.png
Place the following line just after this block to check if the value of the rm variable is any invalid value when you enter data with existing IDs.
Code:
MsgBox rm
If the MsgBox shows invalid values, then make the necessary adjustments to correct it or share your VBA code with us to get a solution.​

Regards,
Seemanto Saha
ExcelDemy
 
Dear bigme,
The following block updates the set of data with any existing ID.
1690786790868.png
Here, the code iterates through 12 rows from where the match was found for the user-given ID No. and updates the first empty row with the user input from the data entry form. The empty rows are checked based on ws.cells(i,1).value expression which depicts values in cells A1, A2, etc. So, if column A of your dataset is completely empty, then the code will assume a non-empty row as empty and update the first existing data with the given ID instead of going to the below rows.
In such cases, we can find the empty row using the reference of a different column (the column with ID No. for example). The modified block is given below.​
Code:
    If matchID = True Then
        For i = rowMatch + 1 To rowMatch + 11
            If ws.Cells(i, idColumn).Value = "" Then
                For j = LBound(ufArr) To UBound(ufArr)
                    ws.Cells(i, j + 1).Value = ufArr(j)
                Next j
                Exit For
            End If
        Next i
    End If
If this is not the case, I may require insight into your dataset structure.

Regards,
Seemanto Saha
Exceldemy​
 

Online statistics

Members online
0
Guests online
7
Total visitors
7

Forum statistics

Threads
371
Messages
1,627
Members
705
Latest member
curioso
Back
Top