I am trying to make a small code which would search a provided range of numbers (which is selected with an input box) for codes from a 'dictionary'. All numbers are used as text, because dictionary numbers contain zeroes in front of them. I made small code based on the info I found on the net but it gives me an error 424 on of the lines of code (I will specify it in the code below)
Here is my workflow:
- Press the button to select the range of cells where the matches from the dictionary will be searched
- Convert the the selected range to Text
- Loop search the values from dictionary in the input-box-selected range and highlight the cells with the match.
- Press another button to reset formatting (to prepare the sheet for pasting another range).
Sub SearchAndFormat_Click()
Dim Dictionary As Variant
Dictionary = Range("O1:O671").value 'the dictionary range whose values to be loop searched
Dim r As Range 'input box to select the range where the dictionary values will be searched
Set r = Application.InputBox("Select range", "Selection Window", Type:=0) '424 error
r.NumberFormat = "@" 'set input box values format to Text to avoid problems
Dim word As Variant
For Each word In Dictionary
r.Find(word).Interior.ColorIndex = 4 'if dictionary values are found in r, add red fill to the cell
Next
End Sub
And here is the code for the clear formatting button in the previously selected range:
Sub ClearFormat_Click()
r.ClearFormats
End Sub
Looking forward to your support!
CodePudding user response:
This error is caused because you've selected the wrong return type for the inputbox.
From microsoft's documention on Application.Inputbox (https://docs.microsoft.com/en-us/office/vba/api/excel.application.inputbox):
Value | Description |
---|---|
0 | A formula |
1 | A number |
2 | Text (a string) |
4 | A logical value (True or False) |
8 | A cell reference, as a Range object |
16 | An error value, such as #N/A |
64 | An array of values |
Therefore you just need to change your 0 to an 8:
Set r = Application.InputBox("Select range", "Selection Window", Type:=8)
EDIT: To resolve the error 91 in the loop:
For Each word In Dictionary
Set target_cell = r.Find(word)
If Not target_cell Is Nothing Then
target_cell.Interior.ColorIndex = 4
End If
Next