To prevent a user from entering a value that is not in a predefined list using Excel VBA, you must use the Worksheet_Change event to monitor cell edits and a Match function to verify if the entered value exists within your source range. If the value is not found, the code triggers a message box and clears the cell, forcing the user to provide a valid entry. This approach is more robust than standard Data Validation because it can be locked against manual overrides and can handle complex logic across multiple sheets.
What You'll Need
- Microsoft Excel installed on a Windows or Mac PC.
- A workbook saved in the
.xlsm(Excel Macro-Enabled Workbook) format to allow VBA code to run. - A defined range of cells containing your "Allowed List" (the values that are considered valid).
- The Developer tab enabled in the Excel Ribbon (File > Options > Customize Ribbon > check Developer).
Step-by-Step
- Prepare Your Data List: Create a list of all acceptable values in a specific column. For example, place your list in cells
A1:A10on a sheet named "Settings". It is highly recommended to turn this range into an official Excel Table (Insert > Table) and name itValidList. This ensures that if you add new items to the list later, the VBA code automatically includes them without needing a manual range update. - Open the VBA Editor: Press
Alt + F11on your keyboard to open the Visual Basic for Applications editor. This window is separate from the main Excel spreadsheet interface. - Select the Correct Sheet: In the Project Explorer pane on the left side of the editor, find the workbook you are working on. Double-click the name of the sheet where you want the "Not in List" restriction to apply (e.g.,
Sheet1). Do not place this code in a standard Module; it must be placed in the Sheet module to trigger theWorksheet_Changeevent. - Insert the Event Handler: At the top of the code window, click the left dropdown menu (which usually says "(General)") and select
Worksheet. In the right-hand dropdown menu, selectChange. Excel will automatically generate the shell of the subroutine:Private Sub Worksheet_Change(ByVal Target As Range). - Define the Target Range: You do not want the code to run every time any cell in the workbook changes, as this would slow down your computer. Use an
Ifstatement withIntersectto specify which cells should be monitored. For example, if you only want to restrict cellB2, your code should start by checking if theTargetcell isB2. - Disable Events: Before the code checks the list, add the line
Application.EnableEvents = False. This is critical. Because the code will clear the cell if the entry is invalid, clearing the cell is itself a "change," which would trigger the code to run again, creating an infinite loop that could crash Excel. - Perform the List Check: Use the
Application.Matchfunction to search for theTarget.Valuewithin yourValidListrange. TheMatchfunction returns a number if the value is found and an error if it is not. By wrapping this in anIf IsError(...)statement, you can identify exactly when a user has entered something that is "not in list." - Handle Invalid Entries: Inside the
If IsErrorblock, add aMsgBoxto notify the user that the value is invalid. Immediately following the message box, useTarget.ClearContentsto remove the illegal entry. - Re-enable Events: At the end of the routine, add
Application.EnableEvents = True. This ensures that Excel continues to monitor changes for future entries. - Test the Logic: Return to your Excel sheet. Try entering a value that exists in your list; it should remain in the cell. Then, try entering a value that does not exist; the warning should appear, and the cell should clear.
Common Mistakes
One of the most frequent errors is forgetting to disable Application.EnableEvents. When the VBA code clears a cell, Excel sees that as a change to the worksheet, which triggers the Worksheet_Change event again. This creates a recursive loop where the code calls itself indefinitely, often leading to the program freezing or crashing. Always pair EnableEvents = False at the start with EnableEvents = True at the end.
Another common mistake is using a fixed range (like A1:A10) instead of a Dynamic Named Range or a Table. If your list of valid items grows over time, a fixed range will ignore any new items added to the bottom of the list, causing the VBA to incorrectly flag valid new entries as "not in list." Using a Table ensures the code always looks at the entire current list.
Case sensitivity is also a recurring issue. By default, VBA's Match function may be sensitive to capitalization depending on how it is called. If your list has "Apple" but the user types "apple", the code might treat it as an invalid entry. To fix this, you can use Option Compare Text at the very top of the module to make all string comparisons case-insensitive.
Tips
To improve user experience, instead of just clearing the cell, you can use Application.Undo. This reverts the cell to its previous value before the invalid entry was made, which is often less frustrating for the user than having the cell left completely blank.
If you have multiple cells that need this restriction, avoid writing separate If statements for every cell. Instead, define a named range in Excel called RestrictedCells and use If Not Intersect(Target, Range("RestrictedCells")) Is Nothing Then. This allows you to manage all restricted cells from the Excel interface without needing to touch the VBA code again.
For professional-grade sheets, combine this VBA approach with standard Data Validation (the dropdown list). While users can sometimes bypass dropdowns by pasting data into the cell, the VBA Worksheet_Change event catches pasted data as well, providing a double layer of security that standard Data Validation cannot offer alone.
Troubleshooting
If the code stops working entirely and doesn't trigger when you change a cell, it is likely that Application.EnableEvents was set to False and then the code crashed before it could be set back to True. When this happens, Excel will stop listening to all events. To fix this, press Ctrl + G in the VBA editor to open the Immediate Window, type Application.EnableEvents = True, and press Enter.
If the code is triggering for every single cell on the sheet, check your Intersect logic. Ensure you have correctly specified the target range. If the Intersect function is missing or improperly written, the Match function will attempt to run on every cell you edit, which can cause significant lag in large spreadsheets.
If the Match function is returning errors for values that you know are in the list, check for trailing spaces. A value like "Apple " (with a space at the end) is not the same as "Apple". Use the Trim() function in VBA around the Target.Value to remove accidental leading or trailing spaces entered by the user.
Frequently Asked Questions
Can I use this to prevent pasting invalid data?
Yes. Unlike standard Excel Data Validation, which can be bypassed by copying and pasting a value into a cell, the Worksheet_Change event triggers regardless of whether the value was typed or pasted, making it the most secure way to enforce a list.
Does this work on Excel for Web?
No. VBA macros do not run in the web browser version of Excel. This functionality requires the desktop application for Windows or macOS. For web-based restrictions, you would need to use Office Scripts (TypeScript), though the logic differs significantly.
How do I make the list come from a different workbook?
You can reference another workbook by using Workbooks("FileName.xlsx").Sheets("SheetName").Range("Range"). However, the source workbook must be open in the same Excel session for the Match function to work reliably.
Can I allow some cells to be blank?
Yes. You should add a check at the beginning of your code: If Target.Value = "" Then Exit Sub. This prevents the code from triggering an "Invalid Entry" warning when a user simply deletes the content of a cell.
Will this slow down my spreadsheet?
If you limit the code to a specific range using Intersect, the performance impact is negligible. However, if you apply the logic to the entire worksheet, you may notice a slight delay during data entry.