【问题标题】:Find date value in a column VBA在列 VBA 中查找日期值
【发布时间】:2016-08-09 13:59:24
【问题描述】:

data on my Excel sheet我想在 A 列中找到一个日期。这是日期格式:“yyyy/mm/dd hh:mm:ss”。它总是一无所获,但我要搜索的日期在 A 列中。 这是我的代码的 sn-p:

Dim LastDay As Date
Dim strdate As String
Dim rCell As Range

strdate = Format(LastDay, "yyyy/mm/dd hh:mm:ss")

Set rCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlValues _
        , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)

If rCell Is Nothing Then
MsgBox ("nothing")
Else

编辑:每个 cmets 的新代码。

Sub Copy()
    Dim LastDayRow As Long
    Dim FirstDayRow As Long
    Dim LastDay As Date
    Dim FirstDay As Date
    Dim rcell As Range

    LastDayRow = Range("E" & Rows.Count).End(xlUp).Row
    Range("E" & LastDayRow).Copy Range("G1")
    FirstDayRow = Range("A" & Rows.Count).End(xlUp).Row
    Range("A" & FirstDayRow).Copy Range("G2")
    LastDay = Cells(LastDayRow, "E").Value
    FirstDay = Cells(FirstDayRow, "A").Value

    Set rcell = Cells.Find(What:=LastDay, After:=Range("A1"), LookIn:=xlFormulas _
                , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)

    If rcell Is Nothing Then
        MsgBox ("nothing")
    End If

End Sub

【问题讨论】:

  • 从您提供的代码来看,您似乎没有为 LastDay 变量设置任何值。
  • 你写的代码是基于 xlValue 找到的。单元格中存储的日期实际上只是数字。因此,您将无法使用 LookIn:=xlValue 找到它
  • 也可能是 format( 将日期转换为字符串格式;而您正在寻找一个日期
  • 我建议您尝试使用 LookIn:=XlFormulas, LookAt:=xlPart

标签: excel vba date


【解决方案1】:

日期类型在 Excel 和 VBA 中都以双精度形式存储。通过将 LookIn 参数更改为 xlFormulas 来搜索双精度值而不是日期。您也可以省略 MatchCase 参数(您使用的是默认值)。

Set rCell = Cells.Find(What:=LastDay, After:=Range("A1"), LookIn:=xlFormulas _
        , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)

请注意,您在这里做了一些无意义的工作......

strdate = Format(LastDay, "yyyy/mm/dd hh:mm:ss")

...因为您只需将其 返回 转换为 Date 即可:

What:=CDate(strdate)

【讨论】:

  • 我更改了您推荐的内容,但仍然没有在 A 列中找到日期。如果我将 LastDay 设置为 Double,宏将停止并显示错误消息。
  • @vergab - 你更新的代码对我来说运行得很好。您遇到了什么错误,在哪里?
  • rcell 值为“无”,但日期在 A 列中。这是 E 列中的最后一个日期:2016/08/02 18:16:21,它也在 A 列中.
  • @vergab - 我无法复制这种行为。当我运行更新后的代码时,它按预期将rcell 设置为$G$1
  • 它是否找到了您让运行代码的日期? rcell 还有其他价值吗?
【解决方案2】:

问题在于日期的格式。此日期格式的“/”:yyyy/mm/dd hh:mm:ss 混淆了 vba 运行。 源文件中的这些代码行解决了这个问题:

Sheet1.Range("A:A").Replace What:="/", Replacement:="."
Sheet1.Range("A:A").NumberFormat = "yyyy/mm/dd hh:mm:ss"
Sheet3.Range("E:E").Replace What:="/", Replacement:="."
Sheet3.Range("E:E").NumberFormat = "yyyy/mm/dd hh:mm:ss"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2011-06-27
    相关资源
    最近更新 更多