excel 2007宏验证输入到单元格的数据,如果不正确则显示msgbox

时间:2013-01-31 14:14:08

标签: excel-vba if-statement excel-2007 msgbox vba

请有人帮忙使用以下代码。它在以下行给出了一个错误:

Set range = "C5:L14"

这是完整的代码:

Private Sub Worksheet_Change(ByVal Target As Excel.range)
Dim ws As Worksheet
Dim range As Worksheet

Set ws = Application.ActiveSheet
Set range = "C5:L14"

If Not Application.Intersect(Target, range("C5:L14")) Is Nothing Then

    If range("C5:L14").Value = "" Then Exit Sub

    If range("C5:L14").Date = "< today()" Then Exit Sub

    If range("C5:L14").Date = "> today()" Then MsgBox ("Future dates not allowed!")

    Else
        MsgBox ("Please enter date as follows yyyy-mm")
    End If

End Sub

日期格式为单元格中的“2013 Jan”。未来的日期是不允许的,用户只应输入日期为“2013-01”。格式应该正确更改它。如果他们输入“2013年1月”,则条件格式化不会提取它。尝试了数据验证,但它只限制我一个。

我需要宏来确保用户不会在指定的单元格中输入错误的日期。

1 个答案:

答案 0 :(得分:4)

您正在尝试的内容也可以在没有VBA的情况下解决。但是我告诉你们这两种方法。拿你的选择

非VBA

选择要应用数据验证的单元格,然后按照以下步骤操作。

第1步

enter image description here

第2步

enter image description here

第3步

enter image description here

第4步

enter image description here

在行动中

enter image description here

<强> VBA

我已对代码进行了评论,因此您在理解代码方面没有任何问题

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rng As Range
    Dim aCell As Range

    '~~> The below two lines are required. Read up more on
    '~~> http://stackoverflow.com/questions/13860894/ms-excel-crashes-when-vba-code-runs/13861640#13861640
    On Error GoTo Whoa
    Application.EnableEvents = False

    '~~> Set your range
    Set rng = Range("C5:L14")

    If Not Application.Intersect(Target, rng) Is Nothing Then
        '~~> Loop through all cells in the range
        For Each aCell In rng
            If aCell.Value <> "" Then
                If aCell.Value > Date Then
                    aCell.ClearContents
                    MsgBox "Future date not allowed in cell " & aCell.Address
                ElseIf IsDate(aCell.Value) = False Then
                    aCell.ClearContents
                    MsgBox "Incorrect date in cell " & aCell.Address
                Else
                    aCell.Value = Format(aCell.Value, "yyyy-mm")
                End If
            End If
        Next
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

希望这有帮助吗?

修改

略有变化。在非VBA方法的第4步中,我错误地键入了“yyyy mm”。将其更改为“yyyy-mm”