繁体   English   中英

使用Vlookup函数时出现运行时错误1004

[英]Run time error 1004 on using Vlookup function

我试图在假期列表中显示日期时突出显示单元格范围。 但是在运行以下代码时,将显示运行时错误1004。 我什至尝试在错误处理程序中处理它; 但它不起作用。 有人可以帮我为什么会发生此错误并解决该错误吗?

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))不是有效的范围引用

也许您想引用Cells(1, i)

此外,您可以利用Application VLookup()方法,该方法将可能的错误包装在返回的变量中,可以使用IsError()函数进行检查,如下所示:

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

这是不使用VBA的条件格式设置方法。

选择范围>条件格式>新规则>使用公式...

输入此公式

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

注意公式中的“ $”。 这应该突出显示在假期列表中找到的所有单元格。

条件格式V查找

您的代码还可以,它在Excel 2010中可用,您的问题是VBA错误处理方法。

转到工具->选项->常规->错误陷阱,然后选中“打破未处理的错误”

在此处输入图片说明

很抱歉,我一直在指vlookup中的第2列。 那就是问题所在。 假期列表是一个单列列表。 因此,vlookup抛出错误。 以及我输入的命名范围可以正常工作的另一件事,甚至实际范围也给出了相同的结果。

子Highlight_cells()昏暗的myrange作为范围

对于i = 1到10

设置myrange = Range(Cells(1,i),Cells(10,i))MsgBox Cells(1,i)temp = Application.VLookup(Cells(1,i),[holidays],1,False)如果不是IsError (temp)然后myrange.Interior.ColorIndex = 3如果结束

接下来我

结束子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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