VBA代码以防止用户将错误数据输入到单元格Excel中

时间:2016-10-21 15:58:06

标签: excel vba excel-vba

大家好我想弄清楚如何编写代码,用户只能在我创建的列表中输入完全相同的数据。我希望代码验证用户条目,并查看条目是否在列表中,如果不是擦除用户输入的数据并给他一条消息。我几乎在那里,但我似乎没有让我的Vlook工作。任何帮助都会非常感激。下面是我写的代码

    Option Explicit
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rng As Range
    Dim aCell As Range
    Dim LU As Range
    Dim Celda As Range


'
    On Error GoTo Whoa
    Application.EnableEvents = False
'~~> This is the range of cells where I want the user to input the data
    Set rng = Range("A1:A15")

    'THis is the range where I want the macro to look if the data the user entered is in the list
    Set LU = Application.WorksheetFunction.VLookup(aCell.Value, Range("F1:F5"), 1, False)


On Error GoTo MyErrorHandler:
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 <> LU Then
                    aCell.ClearContents

MyErrorHandler:
If Err.Number = 1004 Then
aCell.ClearContents
MsgBox "Item Number es Incorrecto - Error en la celda " & aCell.Address

                End If
                End If
            End If
            Next
        End If


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


End Sub

1 个答案:

答案 0 :(得分:0)

使用数据 - 数据验证,设置为按列表允许。对于源位置=$F$1:$F$5。根据您的需求定制选项。不需要VBA。