VBA查找function不能与variables一起使用

我正在创build一个工作表,它需要应用程序来searchexcel工作表中保存在variables中的值。
我正在使用“.Find”function。
我的问题是,当它被存储在一个variables名称中时,找不到的值将被find,尽pipe它在我input一个实际值时有效。

例如:

这工作

Dim cellersd, celltid, ersdcol, tidcol Set cellersd = book.Worksheets(mon & yer).Range("5:5").Find("28/08/2013") Set celltid = book.Worksheets(mon1 & yer1).Range("5:5").Find("30/09/2013") If cellersd Is Nothing Then MsgBox "not found" Else MsgBox cellersd.Column End If If celltid Is Nothing Then MsgBox "not found" Else MsgBox celltid.Column End If 

这不工作

 rsd = Worksheets("workload").Range("p4").Value tid = Worksheets("workload").Range("p3").Value ... Dim cellersd, celltid, ersdcol, tidcol Set cellersd = book.Worksheets(mon & yer).Range("5:5").Find(rsd) Set celltid = book.Worksheets(mon1 & yer1).Range("5:5").Find(tid) If cellersd Is Nothing Then MsgBox "not found" Else MsgBox cellersd.Column End If If celltid Is Nothing Then MsgBox "not found" Else MsgBox celltid.Column End If 

代码中…只是表明我有其他代码执行不同的操作

你能发现我的错误吗? 我也愿意提供其他可以同样工作的search方法的build议。 非常感谢。

也许试试

 rsd = Worksheets("workload").Range("p4").Text tid = Worksheets("workload").Range("p3").Text 

或者如果你想保持.Value.Text不起作用,你应该尝试转换为string:

 rsd = str(rsd) tid = str(tid) 

我相信.Value返回一个date而不是一个string。 而工作代码正在使用一个string。

这应该工作

使用What:=rsd如果它是可变的,使用What:="something"如果它是“”之间的确切词。

如果你需要从variables查找variables,然后使用:

 Set find1 = variable1.Find(What:=variable2, LookIn:=xlValues) 'Both work rsd = Worksheets("workload").Range("P4") tid = Sheets("workload").Range("P3") ... Dim ersdcol, tidcol Dim cellersd As Object Dim celltid As Object Set cellersd = Sheets("mon & yer").Range("5:5").Find(What:=rsd, LookIn:=xlValues) Set celltid = Sheets("mon1 & yer1").Range("5:5").Find(What:=tid, LookIn:=xlValues) If cellersd Is Nothing Then MsgBox "not found" Else MsgBox cellersd.Column End If If celltid Is Nothing Then MsgBox "not found" Else MsgBox celltid.Column End If