Excel VBA UserForm: Search and Update Data
In this article
To build an Excel VBA UserForm that searches and updates data, you need a worksheet with a table of records, a UserForm with a TextBox for the search term and a ListBox to show matches, and command buttons that load the matching row into editable fields and write changes back. The core steps are: insert the UserForm, add controls, write a search routine that loops through the data range and filters matches into the ListBox, populate text boxes when a match is selected, and add an Update button that writes the edited values back to the correct row. This works in any desktop version of Excel that supports VBA (Windows or Mac); the Visual Basic Editor is not available in Excel for the web.
What You'll Need
- Excel desktop (Windows or Mac) with macros enabled. The Developer tab must be visible: if it is not, right-click the ribbon and choose Customize the Ribbon, then tick Developer in the right-hand list. Labels can differ slightly by version and region.
- A worksheet named Data with headers in row 1. For this example the columns are ID (A), Name (B), Email (C), and Status (D), with records starting in row 2.
- A second worksheet named Lists is optional but useful for storing dropdown values.
- A saved workbook in .xlsm format (macro-enabled). Save before you start coding.
Step-by-Step
- Open the Visual Basic Editor. Press Alt+F11 (on Mac, Fn+Alt+F11 or use the Developer tab > Visual Basic). In the Project Explorer, right-click your workbook and choose Insert > UserForm.
- Add controls to the UserForm. From the Toolbox, drag these onto the form: a TextBox named
txtSearch, a CommandButton namedcmdSearchwith caption Search, a ListBox namedlstResults, TextBoxes namedtxtID,txtName,txtEmail,txtStatus, and CommandButtons namedcmdUpdate(caption Update) andcmdClose(caption Close). Add Labels next to each text box for clarity. - Set the ListBox properties. In the Properties window, set
ColumnCountto 4 andColumnWidthsto something like 40;120;140;60 so all four fields are visible. LeaveBoundColumnat 1. - Write the search routine. Double-click
cmdSearchto open its Click event and paste a loop that reads the used range on the Data sheet, compares each row against the search text (usingInStrfor a contains match, or=for exact), and adds matching rows tolstResultsviaAddItemandList. Clear the ListBox first withlstResults.Clear. Example skeleton:Dim ws As Worksheet, r As Long, lastRow As Long Set ws = ThisWorkbook.Worksheets("Data") lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row lstResults.Clear For r = 2 To lastRow If InStr(1, ws.Cells(r, 2).Value, Me.txtSearch.Text, vbTextCompare) > 0 Then With Me.lstResults .AddItem ws.Cells(r, 1).Value .List(.ListCount - 1, 1) = ws.Cells(r, 2).Value .List(.ListCount - 1, 2) = ws.Cells(r, 3).Value .List(.ListCount - 1, 3) = ws.Cells(r, 4).Value End With End If Next r - Populate the edit fields when a result is clicked. In the
lstResults_Clickevent, copy the selected row's values into the text boxes:txtID.Text = lstResults.List(lstResults.ListIndex, 0), and so on for the other columns. This gives the user a starting point to edit. - Write the update routine. In
cmdUpdate_Click, find the row whose ID matchestxtID.Textby looping the Data sheet, then write the text box values back to that row's cells. Wrap the write inApplication.EnableEvents = Falseand restore it afterwards if you have event macros. Show a confirmation withMsgBox "Record updated."and refresh the ListBox by calling the search routine again. - Add validation before writing. Check that
txtID.Textis not blank and that the ID exists; if not, show a message and exit the sub. Optionally validate the email format with a simple check for an @ symbol. - Wire up the Close button. In
cmdClose_Click, useUnload Meto close the form. - Show the form from a normal module. Insert a Module and add a sub such as
Sub ShowForm(): UserForm1.Show: End Sub. Assign it to a button on the sheet or run it with Alt+F8. - Test with sample data. Enter a few records, open the form, search for a partial name, click a result, change a field, and press Update. Confirm the sheet reflects the change and the ListBox refreshes.
Common Mistakes
- Hard-coding row numbers. Always find the last row dynamically with
End(xlUp); otherwise new records are missed or blank rows are read. - Forgetting to clear the ListBox. Without
lstResults.Clear, results from the previous search pile up. - Writing to the wrong row. Match on a unique key such as ID rather than the name, which may repeat.
- Case sensitivity. Use
vbTextCompareinInStrso searches are not case-sensitive unless you want them to be. - Leaving events enabled during writes. If the sheet has Worksheet_Change macros, updating cells can trigger them recursively; toggle
EnableEventsoff and back on. - Not saving as .xlsm. A normal .xlsx file discards the VBA project on save.
Tips
- Use a table (ListObject) instead of a plain range so the data expands automatically; refer to it by name in code.
- Add a ComboBox for the Status field and fill it from the Lists sheet at form load, reducing typos.
- Set
txtSearch.SetFocusin the form's Initialize event so the cursor starts in the search box. - Keep the search loop on a copy of the range in a Variant array for speed on large sheets; reading cell by cell is slow beyond a few thousand rows.
- Add a Clear button that resets all text boxes and the ListBox.
Troubleshooting
- The form does not appear. Check that macros are enabled and that you are running the sub from a standard module, not from the UserForm's own code window.
- Search returns nothing. Confirm the sheet name in code matches the tab exactly, that headers are in row 1 and data starts in row 2, and that the search column index is correct.
- Update writes to the wrong record. Print the matched row number with
Debug.Printin the Immediate window and compare it to the sheet. - Compile error: variable not defined. Add
Option Explicitat the top of each module and declare every variable; this catches typos early. - Changes vanish after closing. Save the workbook after updates, or add
ThisWorkbook.Saveat the end of the update routine if appropriate. - ListBox shows only one column. Set
ColumnCountbefore adding items and checkColumnWidthsis not zero.
Frequently Asked Questions
Can I search across multiple columns at once?
Yes. In the loop, test each column with InStr and combine the results with Or; if any column matches, add the row.
Does this work in Excel for the web or on a Mac?
Excel for the web does not support VBA UserForms. Excel for Mac supports VBA and UserForms, but some controls and the Toolbox behave differently; test on your version.
How do I stop duplicate records being added?
This form only updates existing rows. If you add an Add button later, check the ID against the sheet before writing and reject duplicates.
Can I update without selecting from the ListBox?
Yes, if the user types an exact ID into txtID and presses Update; the code should look up that ID directly. The ListBox is a convenience, not a requirement.
Why does the form slow down with large data?
Cell-by-cell reads are slow. Load the range into a Variant array once, loop the array, and write back in one assignment.