[英]Finding cell with specific value and return position
I am new to VBA and I want to code a function which finds a date, which is stored in a variable, and returns its address.我是 VBA 的新手,我想编写一个 function 来查找日期,该日期存储在变量中,并返回其地址。
This is what I have got so far这是我到目前为止所得到的
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
When I run this snippet, it always returns "no result".当我运行此代码段时,它总是返回“无结果”。 However when I do not use variables and put it like this
但是,当我不使用变量并这样放置时
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
it returns the address of the cell as expected.它按预期返回单元格的地址。
Since I want to use this code snippet later in a larger project, I need this to work with a variable such that it can be used in a loop with a series of different searches.因为我想稍后在一个更大的项目中使用这个代码片段,所以我需要它来处理一个变量,以便它可以在一个循环中使用一系列不同的搜索。
I would be very grateful if somebody can tell me where I am going wrong, or knows an better approach to this.如果有人能告诉我哪里出错了,或者知道更好的方法,我将不胜感激。
I assume you are displaying dates in your worksheet as something like Custom "mm.dd.yy HH:MM:SS" Find is a little finicky about looking for dates and works most predictably when you search for a date string that matches your display format.我假设您在工作表中将日期显示为 Custom "mm.dd.yy HH:MM:SS" Find 对于查找日期有点挑剔,并且当您搜索与您的显示格式匹配的日期字符串时,它的工作方式最可预测.
I think your code will work if you declare dat as String, or if you are working with a Date variable (instead of hard coding the value, as in your example), use我认为如果您将 dat 声明为字符串,或者您正在使用 Date 变量(而不是像您的示例中那样对值进行硬编码),您的代码将起作用,请使用
What:=Format(dat, "mm.dd.yy HH:MM:SS")
Nonetheless @BigBen is correct that the code you have posted should raise an error on尽管如此,@BigBen 是正确的,您发布的代码应该在
dat = "01.05.2009 15:42:00"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.