Excel VBA .Find功能未找到日期

时间:2017-11-29 01:09:53

标签: excel vba excel-vba

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

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

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

然而,在关闭宏编辑器(使用步入调试)后,我可以按Ctrl + F并返回按预期循环显示日期,宏甚至填充窗口!

所以我必须遗漏一些东西,但不会抛出任何错误。

c仍未定义。

count =一个整数,表示在一天中循环的日期

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

d = kill开关,当循环最终导致脚本找到已经复制到左边的第一个日期时,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

1 个答案:

答案 0 :(得分:2)

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

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