excell 2007 macro validate data entered into cell and show msgbox if incorrect

谁都会走 提交于 2019-12-02 07:22:58

What you are trying can be solved without VBA as well. However I am showing you both the methods. Take your pick

NON VBA

Select the cell where you want to apply Data Validation and then follow these steps.

Step 1

Step 2

Step 3

Step 4

In Action

VBA

I have commented the code so you will not have any problem in understanding it

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

Hope this helps?

EDIT:

A slight change. In the Step 4 of the Non VBA Method, I typed "yyyy mm" by mistake. Change that to "yyyy-mm"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!