如何在excel单元格中进行验证,以便它只接受数字和","和" - "但没有字母

时间:2014-12-12 06:03:54

标签: vba excel-vba excel

我想在Excel单元格中提供验证,它只接受数字和逗号(,)和连字符( - )但不接受字母表。

例如,1)123      2)1223456-1223498      3)123456789,986532452

有没有办法实现这个目标?

谢谢

1 个答案:

答案 0 :(得分:0)

全部测试:

作为一项功能: 根据作为字符串传递给它的参数返回True或False。

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

子呼叫功能:
传递字符串以通过函数进行测试,它返回True或False。从您启动代码的任何事件处理程序中调用此方法。就像按钮单击或Cell.Text_change事件一样。

Sub DataValidation()
Dim check As Boolean
Dim tempVal As String

    tempVal = Sheets("Sheet1").Cells(2, 1).Text
    check = ValidateNumber(tempVal)  'Checking Sheet1!A2

    If check = True Then
        MsgBox (tempVal & " Passed Validation")
        'Insert your code here.
    Else
        MsgBox (tempVal & " isn't a valid number.  Input only numbers, commas, hyphens")
        Sheets("Sheet1").Cells(2, 1) = ""     'Clear the Cell of the invalid entry.
        Sheets("Sheet1").Cells(2, 1).Select   'Return the focus to the cell in question.
    End If
End Sub

作为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变量,而不是完成所有这些操作。