如何限制单元格仅输入数字

use*_*518 5 excel vba excel-vba

我有一个excel文件,验证一列只输入数字,但格式化为数字小于18,将添加前导零.但现在第15位后的数字将转换为0 ex:"002130021300020789",九将更改为0.将列转换为文本后,它接受但我无法添加前导零并且无法限制输入onlu数字.

感谢任何帮助..提前感谢.

Sid*_*out 2

MS 文章:Excel 遵循有关如何存储和计算浮点数的IEEE 754 规范。因此,Excel 仅存储数字中的 15 位有效数字,并将第 15 位之后的数字更改为零。

要获得数字格式并确保用户仅输入数字,您可以执行此操作。我假设您正在验证范围 A1 中的文本。请酌情修改。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        '~~> If entered text is not a number then erase input
        If Not IsNumeric(Range("A1").Value) Then
            MsgBox "invalid Input"
            Application.Undo
            GoTo LetsContinue
        End If

        Range("A1").Value = "'" & Format(Range("A1").Value, "000000000000000000")
    End If

LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub
Run Code Online (Sandbox Code Playgroud)

跟进

如果您要复制和粘贴,则必须首先将范围 G11:G65536 手动格式化为文本,然后使用此代码

快照(粘贴数值时)

在此输入图像描述

快照(粘贴非数值时)

在此输入图像描述

代码

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Dim cl As Range

    Application.EnableEvents = False

    If Not Intersect(Target, Range("G11:G" & Rows.Count)) Is Nothing Then
        For Each cl In Target.Cells
            '~~> If entered text is not a number then erase input
            If Not IsNumeric(cl.Value) Then
                MsgBox "invalid Input"
                Application.Undo
                GoTo LetsContinue
            End If

            cl.Value = "'" & Format(cl.Value, "000000000000000000")
        Next
    End If

LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub
Run Code Online (Sandbox Code Playgroud)