使VBA Form文本框仅接受数字(包括+,-和.) [英] Making VBA Form TextBox accept Numbers only (including +, - and .)

查看:275
本文介绍了使VBA Form文本框仅接受数字(包括+,-和.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的textBox,我想验证其输入,包括"+",-"和".这是我尝试过的

I have simple textBox and I want to validate its input including "+" , "-" and "." here is what I have tried

Private Sub DisplayValue_TextBox_Change()
If Not IsNumeric(DisplayValue_TextBox.Value) Then
               MsgBox "Only numbers allowed"

      End If
End Sub

但这只接受0-9的数字,不能为负,正值或浮点值.

But this only accepts numbers 0-9 no negative, positive value or float value..

推荐答案

进一步我的评论:

考虑带有Textbox1和CommandButton1的示例Userform1

Consider a sample Userform1 with a Textbox1 and a CommandButton1

TextBox1中输入任何内容时,将触发更改事件-即.键入一个字符将触发Change()事件并传递当前值,因此即使您键入负号,当前逻辑也会失败.

when you enter anything in the TextBox1 the change event fires - ie. typing one character fires the Change() event and passes the current value so even when you type in the negative sign your current logic fails.

您需要使用另一个事件,例如_AfterUpdate()_Exit(),而第二个事件具有重点,因为您可以取消该事件:)

What you need is to use another event like _AfterUpdate() or _Exit() with an amphasis on the second one because your can cancel the event :)

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Not IsNumeric(TextBox1.Value) Then
        MsgBox "only numbers allowed"
        Cancel = True
    End If
End Sub

您可以在此处找到事件:

You can find events here:

这篇关于使VBA Form文本框仅接受数字(包括+,-和.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆