简体   繁体   English

VBA查找功能不起作用

[英]VBA Find Function not working

I am trying to use vba code to search for a value in another sheet and return the row number so the adjacent cell can be filled in with a string.我正在尝试使用 vba 代码在另一张表中搜索一个值并返回行号,以便可以用字符串填充相邻的单元格。 The problem is that the "findrow" is returning blank.问题是“findrow”返回空白。 The ".find(findrng) shows as 14/01/17 when I try to Run and hover over that part.当我尝试运行并将鼠标悬停在该部分上时,“.find(findrng) 显示为 14/01/17。

If I change the Findrng to a word such as "Home" and enter this on the file the code returns the correct row number so the problem must be with the date.如果我将 Findrng 更改为诸如“Home”之类的单词并将其输入文件中,则代码将返回正确的行号,因此问题一定出在日期上。 Can anyone help with using .Find for dates?任何人都可以帮助使用 .Find 日期吗?

Private Sub Enter_Click()
Dim FindWor As Range
Dim Findrng As String
Dim FindRowNumber As Long

Findrng = Me.Date1
With Worksheets("Data").Range("$A:$A")
Set FindWor = .Find(what:=Findrng)
FindRowNumber = FindWor.Row

.Cells(FindRowNumber, 2).Value = Me.Event1
End With

 End Sub

Thanks谢谢

Steven史蒂文

The Find method has a number of optional arguments, that don't have predefined defaults, but rather, they default to the values that were last used, either through code, or through the Excel user interface. Find方法具有许多可选参数,它们没有预定义的默认值,而是通过代码或Excel用户界面默认为最后使用的值。 You should explicitly state all of the arguments in order to get consistent and expected behavior . 您应该明确声明所有参数,以便获得一致且预期的行为

The Range.Find method is defined as: Range.Find方法定义为:

Function Find(What, Optional After, Optional LookIn, Optional LookAt, Optional SearchOrder, Optional SearchDirection As XlSearchDirection = xlNext, Optional MatchCase, Optional MatchByte, Optional SearchFormat) As Range

You need to provide values for all of those arguments, even though they're marked as Optional 您需要为所有这些参数提供值,即使它们被标记为“ Optional

The Find method can also return a Nothing reference if a match cannot be found, so you need to test for Nothing before inspecting the Row property. 如果Find匹配项, Find方法也可以返回Nothing引用,因此您需要在检查Row属性之前测试Nothing For example: 例如:

Set FindRow = .Find(Find)
If Not FindRow Is Nothing Then
    FindRowNumber = FindRow.Row
End If

你必须Dim FindRowNumber如

This : 这个 :

Set FindWor = .Find(what:=Findrng)

Findrng is a string ,and the data there is date , so it will definitely return nothing. Findrng是一个字符串,并且数据中有date,因此它绝对不会返回任何内容。

If you are not sure what will your code search weather string or date , first find the value as string , if not found convert it to date and do a search again 如果不确定您的代码将搜索天气字符串或日期的内容,请首先以字符串形式找到该值,如果找不到,则将其转换为日期,然后再次进行搜索

    Set FindWor = .Find(what:=Findrng)

    if  FindWor  is nothing  then
           Set FindWor = .Find(what:=cdate(Findrng))
    end if

我有 2 张工作表,它们都带有用于查找值的连接字符串,并且 .Find 仅在我指定 LookIn:=xlValues 选项后才对这些工作表起作用。

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

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