首页 > 解决方案 > 如何同时使用 IsNumeric 和 Not IsNumeric 函数?

问题描述

我有一个通过 Excel 与条形码阅读器集成的股票程序。
使用以下代码,我可以将数字条形码读取到文本框。

条码如1010108693457248273

If Not IsNumeric(TextBox2.Value) Then
    TextBox2.SetFocus
    TextBox2.SelStart = 1
    TextBox2.SelLength = Len(TextBox2.Text)
    Cancel = True
    Else
End If

当我尝试将条形码读取为730MT30151时,上面的代码行不起作用。
如果我删除Not它有效。

但是我无法读取数字条形码。

If IsNumeric(TextBox2.Value) Then
    TextBox2.SetFocus
    TextBox2.SelStart = 1
    TextBox2.SelLength = Len(TextBox2.Text)
    Cancel = True
    Else
End If

我想混合两种代码。

标签: excelvba

解决方案


这段代码基本上意味着取消(Cancel = True)所有包含文本(Not IsNumeric)的输入。

If Not IsNumeric(TextBox2.Value) Then
    TextBox2.SetFocus
    TextBox2.SelStart = 1
    TextBox2.SelLength = Len(TextBox2.Text)
    Cancel = True
Else
End If

实际上,代码只是对数字的限制。因此,如果您现在想允许数字字母,只需完全删除该(限制)代码。

如果您想保留选择和焦点内容,请保留以下行:

TextBox2.SetFocus
TextBox2.SelStart = 1
TextBox2.SelLength = Len(TextBox2.Text)

推荐阅读