VBA:如果单元格格式是日期,则执行某些操作

时间:2016-03-10 17:24:37

标签: excel vba excel-vba date format

我在设置宏的条件时遇到问题。 应该这样做:

If CELL_A is * **AND** CELL_B is **DATE** then....

    Sub kontrolafyzprav()

radek = 4

  With List1

    Do While .Cells(radek, 3) <> ""
        If .Cells(radek, 3) = "DOM" And .Cells(radek, 7).NumberFormat = "General" Then
            .Cells(radek, 3).Interior.Color = RGB(255, 150, 150)
            .Cells(radek, 7).Interior.Color = RGB(255, 150, 150)

        ElseIf .Cells(radek, 3) = "MO" And .Cells(radek, 7).NumberFormat = "d/m/yyyy" Then
            .Cells(radek, 3).Interior.Color = RGB(255, 150, 150)
            .Cells(radek, 7).Interior.Color = RGB(255, 150, 150)
                    ' :(    :(     :(     :(

        End If
                radek = radek + 1
    Loop

  End With

End Sub

在与ElseIf .Cells(radek, 3) = "MO" And .Cells(radek, 7).NumberFormat = "d/m/yyyy" Then一致的情况下,我尝试了所有我能想到的事情。

第一组条件很有效,但我不能得到第二组条件:/

任何帮助?

1 个答案:

答案 0 :(得分:3)

原生VBA IsDate Function可以很好地确定单元格的内容,看它是否包含日期。 Range.Value property(但不是Range.Value2 property)保留的区域日期特定设置有助于确定。

Sub kontrolafyzprav()
    Dim raek As Long

    radek = 4

    With List1
        Do While .Cells(radek, 3) <> ""
            If .Cells(radek, 3) = "DOM" And .Cells(radek, 7).NumberFormat = "General" Then
                .Cells(radek, 3).Interior.Color = RGB(255, 150, 150)
                .Cells(radek, 7).Interior.Color = RGB(255, 150, 150)

            ElseIf .Cells(radek, 3) = "MO" And IsDate(.Cells(radek, 7)) Then
                .Cells(radek, 3).Interior.Color = RGB(255, 150, 150)
                .Cells(radek, 7).Interior.Color = RGB(255, 150, 150)
                        ' :(    :(     :(     :(
            End If
            radek = radek + 1
        Loop
    End With

End Sub

IsDate函数不会被无效的文本愚弄 - 看起来像是一个日期。