Range.find 以日期作为参数

问题描述 投票:0回答:1

我有一个表(我们称之为 tb1),其中有一个日期列。

我需要使用 tb1_date 作为键在 tb2 (上面有日期)中搜索,并且它必须返回相同日期所在的 tb2 行号

for i = 1 to tb1_length
    v1 = range("A" & i).value    'date from tb1, i is just a random row
    msgbox range("D1:D20").find(v1).row  'search for the row number in tb2 (say its D1:D20)

现在,每当我使用日期作为搜索参数时,这都会导致运行时错误 91 或类似错误

我尝试将日期类型转换为长类型(甚至格式化它),但搜索没有成功

excel vba range
1个回答
0
投票

如果未找到匹配项,则返回值将为

Nothing
- 在这种情况下,表达式
Find(v1).Row
相当于
Nothing.Row
,这将导致错误 91(因为未设置 Object 变量)

如果您要搜索的值不存在

Find(v1)
将返回
Nothing
从而导致错误

要解决此问题,您必须检查您的返回是否为 Nothing,如果不是,则仅继续获取行

Dim match As Range

Set match = Range("D1:D20").Find(v1)
If Not match Is Nothing Then
    MsgBox (match.Row)
End If
© www.soinside.com 2019 - 2024. All rights reserved.