查找具有特定值和返回位置的单元格

时间:2019-10-30 16:26:23

标签: excel vba

我是VBA的新手,我想对一个函数进行编码,该函数可以找到一个存储在变量中的日期并返回其地址。

这是我到目前为止所得到的

Dim ran As Range
Dim dat As Date
dat = "01.05.2009  15:42:00"

Set ran = Cells.Find(What:=dat, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

If ran Is Nothing Then
    MsgBox ("no result")
    Else
    MsgBox (ran.Address)

End If

运行此代码段时,它始终返回“无结果”。但是,当我不使用变量并像这样放置它

Dim ran As Range
Dim dat As Date

Set ran = Cells.Find(What:="01.05.2009  15:42:00", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

If ran Is Nothing Then
    MsgBox ("no result")
    Else
    MsgBox (ran.Address)

End If

它按预期返回单元格的地址。

由于我想稍后在较大的项目中使用此代码段,因此我需要使用此代码段以使用变量,以便可以在循环中使用一系列不同的搜索来使用它。

如果有人可以告诉我我要去哪里错,或者知道更好的解决方法,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我假设您在工作表中以“自定义”(mm.dd.yy HH:MM:SS)之类的方式显示日期,“查找”对于查找日期有些挑剔,并且在搜索与日期匹配的日期字符串时最可预测您的显示格式。

我认为,如果您将dat声明为String,或者您正在使用Date变量(而不是像示例中那样对值进行硬编码),请使用

What:=Format(dat, "mm.dd.yy HH:MM:SS")

尽管如此,@ BigBen是正确的,因为您发布的代码应该引发错误

dat = "01.05.2009  15:42:00"