使用宏进行十进制数据验证

时间:2019-02-04 06:32:34

标签: excel vba

我有一个启用了宏的工作表,在该工作表中,我对要调节数据输入的列进行了数据验证。我无法在excel中使用常规数据验证功能,因为它无法正常工作,因为我们无法从其他来源复制数据(这是我的要求)。因此,我正在通过宏实施数据验证。我有一种情况,一列只能输入十进制数据。条件如下所示,输入数据的长度为9,仅构成2个小数位。我已经为此验证部分编写了一个无效的宏(当我发出无效的输入宏时不会触发,因此不会弹出msgbox),此时我被卡住了。请在这里帮助我找到其他的if条件验证。我写的宏如下:

Set AffectedCells = Intersect(Target, Target.Parent.Range("F:F"))

If Not AffectedCells Is Nothing Then

For Each Cell In AffectedCells
        If Not (Cell.Value * (10 ^ 2) Mod 10) <> 0 Then

            MsgBox "The value you entered is not valid." 

            Application.Undo 'undo insert
            Exit Sub 'stop checking after one invalid data was found.
        End If

2 个答案:

答案 0 :(得分:0)

这需要粘贴到要运行宏的工作表的工作表代码空间上。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim xCell As Range, AffectedCells As Range

Set AffectedCells = Intersect(Target, Target.Parent.Range("F:F"))

If Not AffectedCells Is Nothing Then
    For Each xCell In AffectedCells
            If Not (xCell.Value * (10 ^ 2) Mod 10) <> 0 Then
                MsgBox "The value you entered is not valid."
                    Application.EnableEvents = False
                        Application.Undo
                    Application.EnableEvents = True
                Exit Sub
            End If
    Next xCell
End If

End Sub

答案 1 :(得分:0)

这是您要尝试的吗?我已对代码进行了注释,因此您应该不难理解它。但是,如果这样做,那就问一下。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCell As Range, AffectedCells As Range

    On Error GoTo Whoa

    Application.EnableEvents = False

    Set AffectedCells = Intersect(Target, Columns(6))

    If Not AffectedCells Is Nothing Then
        For Each xCell In AffectedCells
            '~~> Avoid cases like IP address 10.1.2.234
            '~~> Check if the number contains decimal
            If IsNumeric(xCell.Value) And _
            Int(xCell.Value) <> xCell.Value Then
                '~~> Check the position of the decimal
                '~~> Check the length of the string
                If Mid(xCell.Value, Len(xCell.Value) - 2, 1) <> "." Or _
                Len(xCell.Value) > 9 Then
                    '
                    '~~> INVALID INPUT: Do what you want
                    '

                    'MsgBox "The value you entered is not valid."
                    'Application.Undo
                    'Exit For
                End If
            End If
        Next xCell
    End If

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