【问题标题】:Excel VBA .Find Function not finding a dateExcel VBA .Find函数找不到日期
【发布时间】:2017-11-29 09:58:53
【问题描述】:

我正在使用以下 VBA 代码选择列中每个数据的第一个实例,并将其复制到左侧的新列中。

由于我不明白的原因,.Find 方法在我的工作表中找不到任何日期。

日期格式为 03/10/2017 17:05:00

但是,在关闭宏编辑器后(已使用 step-into 进行调试),我可以按 Ctrl + F 并 Return 按预期循环浏览日期,宏甚至会填满窗口!

所以我一定遗漏了一些东西,但没有抛出任何错误。

c 仍未定义。

count = 一个整数,表示要在日期之间循环的月份中的哪一天

c = 找到搜索字符串的范围(或者在这种情况下应该是)

d = 终止开关,当循环最终导致脚本找到已复制到左侧的第一个日期时,d 应变为 1 并结束循环。由于此错误,未经测试。

cell = 纯粹用于用#N/A 填充新列中的剩余单元格

您可能会说我在这里非常业余,我欢迎并感谢任何帮助或反馈。

Sub LabelMaker()
'
' LabelMaker Macro
'
Dim count As Integer
count = 2
Dim c As Range
Dim s As String
Dim d As Integer
d = 0
Dim cell As Range
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
    Columns("C:C").Insert Shift:=xlToRight
    Range("C1") = "Labels"
    Do
        s = CStr(count) & "/10/2017"
        Set c = .Range("D:D").Find(s, LookIn:=xlValues, LookAt:=xlPart)
            If Not c Is Nothing Then
                If IsEmpty((c.Offset(rowOffset:=0, columnOffset:=-1))) Then
                    c.Copy _
                        Destination:=c.Offset(rowOffset:=0, columnOffset:=-1)
                Else
                    d = 1
                End If
            End If
            count = count + 1
            If count = 32 Then
                count = 1
            End If
    Loop While d = 0
    For Each cell In Range("C:C")
        If IsEmpty(cell) Then
            cell = "#N/A"
        End If
    Next
End With
'
End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您的电子表格可能包含实际日期,而不仅仅是看起来像日期的文本,因此请将您的字符串转换为日期:

    Set c = .Range("D:D").Find(CDate(s), LookIn:=xlValues, LookAt:=xlPart)
    

    【讨论】:

    • 该死,我是如此接近...非常感谢。
    • @Sam3000 而且,当您决定不喜欢有一百万个包含"#N/A" 的单元格时,您可以考虑将For Each cell In Range("C:C") 更改为For Each cell In .Range("C1:C" & .Cells(.Rows.Count, "D").End(xlUp).Row) ;-)
    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2013-01-05
    相关资源
    最近更新 更多