Vba 如何在excel单元格中进行验证,使其只接受数字和“,”和“-”,而不接受字母
我想在Excel单元格中提供验证,它只接受数字、逗号和连字符,而不接受字母 e、 g,1123 2 1223456-1223498 3 123456789986532452 有没有办法做到这一点 感谢所有测试: 作为一项功能: 根据作为字符串传递给它的参数返回True或FalseVba 如何在excel单元格中进行验证,使其只接受数字和“,”和“-”,而不接受字母,vba,excel,Vba,Excel,我想在Excel单元格中提供验证,它只接受数字、逗号和连字符,而不接受字母 e、 g,1123 2 1223456-1223498 3 123456789986532452 有没有办法做到这一点 感谢所有测试: 作为一项功能: 根据作为字符串传递给它的参数返回True或False Function ValidateNumber(tempVal As String) As Boolean Dim result As Boolean tempVal = Replace(tempVal,
Function ValidateNumber(tempVal As String) As Boolean
Dim result As Boolean
tempVal = Replace(tempVal, "-", "") 'remove all hyphens
tempVal = Replace(tempVal, ",", "") 'remove all commas
'what is left of tempVal at this point is to be tested.
If (Not IsNumeric(tempVal) And (tempVal <> "")) Then
result = False
Else
result = True
End If
'Function returns True or False
ValidateNumber = result
End Function
作为InputBox和MessageBox测试:
这可以独立于工作表运行。使用输入框获取测试值,使用消息框显示结果
Sub ValidateNumberCheck()
Dim cellVal As String
Dim tempVal As String
cellVal = InputBox("Input some text to check", "Validation Check")
tempVal = Replace(cellVal, "-", "")
tempVal = Replace(tempVal, ",", "")
If (Not IsNumeric(tempVal) And (tempVal <> "")) Then
MsgBox ("Not a valid character. Please input only numbers, commas, or hyphens.")
Else
MsgBox ("Input Passed Validation.")
End If
End Sub
注意:请务必记住,对于最后一个示例,如果您使用它,那么您使用的是cellVal,而不是tempVal。我们只是测试tempValue,因为我们知道它是cellVal的一个副本,但是当它通过测试时,所有的逗号和连字符都被删除了,它需要重新格式化。因此,您没有经历所有这些,而是保留了存储原始输入的原始cellVal变量。。这方面的例子不胜枚举。你查过了吗?此外,请包括您编写的任何代码、遇到的错误或取得的进展等。我搜索了这么多示例。找不到这样的。由于逗号和连字符被视为文本,如果我只将单元格设为numreic,则无法接受。这就是我面临的问题。谢谢Rosenburg。感谢您的帮助:
Sub ValidateNumberCheck()
Dim cellVal As String
Dim tempVal As String
cellVal = InputBox("Input some text to check", "Validation Check")
tempVal = Replace(cellVal, "-", "")
tempVal = Replace(tempVal, ",", "")
If (Not IsNumeric(tempVal) And (tempVal <> "")) Then
MsgBox ("Not a valid character. Please input only numbers, commas, or hyphens.")
Else
MsgBox ("Input Passed Validation.")
End If
End Sub