简体   繁体   中英

Run time error 1004 on using Vlookup function

Im trying to highlight range of cells when a date is present in the list of holidays. But on running the below code, the Run time error 1004 is displayed. I have even tried handling it in error handler; but it is not working. Can somebody please help me why this error is occuring and resolve the same?

Sub highlight_cells()
Dim myrange As Range
On Error GoTo myerr:
For i = 1 To 10
Set myrange = Range(Cells(1, i), Cells(10, i))
temp = Application.WorksheetFunction.VLookup(Range(Cells(1, i)), [holidays], 2, False)
If (Application.WorksheetFunction.IsNA(temp)) Then
myrange.Interior.Color = 3
End If
Next i

myerr:
If Err.Number = 1004 Then
MsgBox "vlookup error"
End If
End Sub

Range(Cells(1, i)) isn't a valid range reference

maybe you wanted to reference Cells(1, i)

furthermore you can exploit the Application VLookup() method that wraps the possible error in the returned variant variable that you can check with IsError() function like follows:

Dim temp As Variant
For i = 1 To 10
    Set myrange = Range(Cells(1, i), Cells(10, i))
    temp = Application.VLookup(Cells(1, i), [holidays], 2, False)
    If Not IsError(temp) Then Cells(1, i).Interior.Color = 3
Next i

Here is a conditional formatting method, without using VBA.

Select your range > Conditional Formating > New Rule > Use a formula ...

Enter this formula

=VLOOKUP($A2,$J$2:$K$6,1,FALSE)

Take care of the "$" in the formula. This should highlight all cells that were found in the holidays list.

条件格式V查找

Your code is okay , It worked in Excel 2010 , Your problem is with VBA Error handling method.

Go to Tools --> Options -->General --> Error Trapping And check "Break on unhanded Errors"

在此处输入图片说明

sorry all these times I was referring to column 2 in vlookup. That was causing the problem. The list of holiday is a single column list. Hence vlookup was throwing error. ANd one more thing the named ranges work as I have entered and even the actual range also gives the same result.

Sub highlight_cells() Dim myrange As Range

For i = 1 To 10

Set myrange = Range(Cells(1, i), Cells(10, i)) MsgBox Cells(1, i) temp = Application.VLookup(Cells(1, i), [holidays], 1, False) If Not IsError(temp) Then myrange.Interior.ColorIndex = 3 End If

Next i

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM