VBA - 在一系列单元格中搜索日期,返回单元格地址

时间:2018-03-19 22:46:40

标签: excel vba excel-vba

我正在尝试编写一个函数来搜索在相邻工作表的单元格区域中作为参数输入的特定日期。在找到日期时,函数应返回一个字符串“found:”和单元格引用。

所有似乎都运行得很好,但即使在日期格式中存在(故意输入)日期时,函数也会返回“无”,无论是在单元格区域还是在调用函数时引用的单元格中。 / p>

在使用日期时调用查找时,我是否遗漏了一些重要内容?

注意,该函数在另一个工作表中查看与其调用的行相同的行。这可能有助于解释我如何设置rng

    Public Function d_scan(targ As Date) As String
      Dim ws As Worksheet
      Dim targetSheet As Worksheet
      Dim ret As String
      Dim rng As String
      Dim scanner As Date
      Dim found As Range

      Set targetSheet = ThisWorkbook.Worksheets("2018")
      Set ws = Application.Caller.Worksheet
      Let intRow = Application.Caller.Row
      Let intCol = Application.Caller.Column

      Let rng = "F" & intRow & ":" & "X" & intRow

      Set found = targetSheet.Range(rng).Find(What:=targ, LookAt:=xlWhole)

      If found Is Nothing Then
        Let ret = "nothing"
      Else
        Let ret = "found: " & found
      End If

      d_scan = ret

 End Function

2 个答案:

答案 0 :(得分:2)

日期问题非常微妙,它们的解决方案可能取决于实际情况(使用的变量类型,工作表中使用的数据格式,......)

首先,您可能需要:

  • 指定所有相关的Find()方法参数,因为未定义的方法参数将根据其最后一次使用隐式假设(即使是从Excel UI!)

  • 通过Date函数将String转换为CStr()

所以,你可能想尝试这段代码:

Option Explicit

Public Function d_scan(targ As Date) As String
    Dim rng As String
    Dim found As Range
    Dim intRow As Long

    intRow = Application.Caller.Row
    rng = "F" & intRow & ":" & "X" & intRow

    Set found = ThisWorkbook.Worksheets("2018").Range(rng).Find(What:=CStr(targ), LookAt:=xlWhole, LookIn:=xlValues) ' specify 'LookIn' parameter, too

    If found Is Nothing Then
        d_scan = "nothing"
    Else
        d_scan = "found: " & found
    End If
End Function

答案 1 :(得分:1)

我认为你将日/小时/分钟/秒与日/小时/分钟/秒进行比较并且没有匹配(一切都太具体)。我用这个按摩targ进入"今天"在凌晨12:00,你需要做一些事情来按下这样的表格上的数据以及range.find工作。

targ = Application.WorksheetFunction.Floor(targ, 1)

我建议使用range.find以外的方法...也许,在寻找targ和小于1的单元格之间的区别?

相关问题