VBA isnumber istext函数问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6187848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA isnumber istext function problem
提问by Daniel Faria
im trying to check if a number is a text or number in a banking system. If the value is incorrect it should erase and send an error message, but my code isnt working at all... can someone help me? here is the code:
我试图检查一个数字是银行系统中的文本还是数字。如果值不正确,它应该删除并发送错误消息,但我的代码根本不起作用......有人可以帮助我吗?这是代码:
Private Sub TextBox1_Change()
name = TextBox1
If Application.IsText(name) = True Then
IsText = True
Else
MsgBox "Insert only words"
Selection.name.Delete
End If
End Sub
回答by jonsca
I think you should be using name = TextBox1.Text
instead. It's probably giving you an error on that line.
我认为你应该使用它name = TextBox1.Text
。它可能会在那条线上给你一个错误。
Also, you may want to wait until the user is finished typing the response, I believe the changed event will run each time a character is pressed. The AfterUpdate
will run after you tab or click away from the textbox.
此外,您可能希望等到用户完成输入响应,我相信每次按下字符时更改的事件都会运行。在AfterUpdate
您标签后继续运行还是从文本框点击即可。
And really, instead of deleting the response (which I don't think will work), you should simply set the textbox blank back to an empty string.
实际上,与其删除响应(我认为这行不通),您应该简单地将文本框设置为空字符串。
Private Sub TextBox1_AfterUpdate()
If Not MyIsANumber(TextBox1.Text) Then
MsgBox ("It's Text")
Else
TextBox1.Text = ""
End If
End Sub
Function MyIsANumber(str As String) As Boolean
For i = 1 To Len(str)
If IsNumeric(Mid(str, i, 1)) Then
MyIsANumber = True
Exit Function
End If
Next
MyIsANumber = False
End Function
I'm sure the code could be structured better, but there's something along the lines of what you need. In this case, it just wipes the textbox if there is a number entered. Obviously, things will need to be the opposite for your textbox that you want to contain a number.
我确信代码的结构可以更好,但有些东西符合您的需求。在这种情况下,如果输入了数字,它只会擦除文本框。显然,对于您想要包含数字的文本框,事情需要相反。
回答by ragoertz
Have you considered the vartype() function? https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function
你考虑过 vartype() 函数吗?https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function