【问题标题】:VBA - search for a date in a range of cells, returning cell addressVBA - 在一系列单元格中搜索日期,返回单元格地址
【发布时间】:2018-03-20 23:40:20
【问题描述】:

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

一切似乎都运行良好,但即使在单元格区域和调用函数时引用的单元格中存在(故意输入的)日期格式的日期时,该函数也会返回“无”。

在使用 Date 时调用 find 时是否遗漏了一些关键信息?

请注意,该函数在另一张表中与调用它的同一行中查找。这可能有助于解释我如何设置 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

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

    首先,您可能需要:

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

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

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

    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
    

    【讨论】:

    • @bjm,有什么反馈吗?
    • 感谢您 - 完美运行。我想知道将其转换为字符串是否会有所帮助。 elliot(下)对 Date 的性质提出了一个很好的观点,这当然没有帮助。谢谢你们。
    • 不客气。在 VBA 中,我有时必须转换为字符串,有时转换为 double……这是一个艰难的世界!
    【解决方案2】:

    我认为您将日/小时/分钟/秒与日/小时/分钟/秒进行比较并且没有匹配项(一切都太具体了)。我用它在上午 12:00 将 targ 按摩到“今天”,但你需要做一些事情来像这样按摩工作表上的数据,以便 range.find 工作。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多