How to restrict a cell to input only numbers

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I have an excel file, validating one column to enter numbers only but it is formatted as if the number is less than 18 the leading zeros will be added. But now the number after 15th digit it will be converting to 0 ex: "002130021300020789", the nine is changed as 0. After converting the column to text, its accepting but i am not able to add the leading zeros and not able to restrict to input onlu numbers.

Appreciate any help.. thanks in advance.

回答1:

MS Article: Excel follows the IEEE 754 specification on how to store and calculate floating-point numbers. Excel therefore stores only 15 significant digits in a number, and changes digits after the fifteenth place to zeroes.

To get your number formatting and to also ensure that the user enters only numbers you can do this. I am assuming that you are validating the text in Range A1. Please amend as applicable.

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 

FOLLOWUP

If you are copying and pasting then you will have to first format the Range G11:G65536 manually as TEXT and then use this code

SNAPSHOT (When Pasting Numeric Values)

SNAPSHOT (When Pasting Non Numeric Values)

CODE

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 


回答2:

First you can change the format of the cell to text

Range("A1").NumberFormat = "@" 

Then you can add zeroes

cellvalue2 = Format(cellvalue1, "000000000000000")  // for numeric fields                     or               = TEXT(cellvalue1,"000000000000000")    // for textfields 


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