I would like to enter a value in G1 and on worksheet change all cells in A2:F500 are…
- User
I would like to enter a value in G1 and on worksheet change all cells in A2:F500 are searched for the existence of the value in any position in the range irrespective of font case. For all values found the cell will be highlighted yellow. Can you please write a VBA code to do this.
- Assistant
Sure! Here is the VBA code to achieve what you're looking for:
Private Sub Worksheet_Change(ByVal Target As Range) Dim searchValue As String Dim cell As Range 'Specify the search value in G1 searchValue = Range("G1").Value 'Iterate through each cell in A2:F500 For Each cell In Range("A2:F500") 'Check if the cell contains the search value If InStr(1, cell.Value, searchValue, vbTextCompare) > 0 Then 'Highlight the cell cell.Interior.Color = RGB(255, 255, 0) 'Yellow Else 'Clear the highlighting if the search value is not found cell.Interior.ColorIndex = xlNone End If Next cell End SubTo implement this code, follow these steps:
- Right-click on the sheet tab where you want the code to apply (e.g., Sheet1) and select "View Code."
- In the Visual Basic for Applications editor, paste the above code.
- Close the VBA editor.
Now, whenever you change the value in cell G1, the code will search for that value in range A2:F500 and highlight the cells containing the value in yellow.
- User
I would like to search within values
- Assistant
Apologies for the confusion. To search within values instead of just within cells, you can modify the code as follows:
Private Sub Worksheet_Change(ByVal Target As Range) Dim searchValue As String Dim cell As Range 'Specify the search value in G1 searchValue = UCase(Range("G1").Value) 'Iterate through each cell in A2:F500 For Each cell In Range("A2:F500") 'Check if the cell value contains the search value If InStr(1, UCase(cell.Value), searchValue, vbTextCompare) > 0 Then 'Highlight the cell cell.Interior.Color = RGB(255, 255, 0) 'Yellow Else 'Clear the highlighting if the search value is not found cell.Interior.ColorIndex = xlNone End If Next cell End SubThis modified code converts both the search value and the cell value to uppercase using the
UCasefunction. This ensures that the search is case-insensitive.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.