选择案例是< 0为负数

时间:2012-06-28 12:51:14

标签: ms-access

最初的简单验证代码是在我看来非常矛盾的情况下转换的。

以下代码返回“Good work!”当我在InputBox弹出窗口输入负数时

Dim myvar As String

myvar = InputBox("input a positive number, please")

If IsNumeric(myvar) Then
    myvar = CDbl(myvar)
    Select Case myvar
    Case Is < 0
        MsgBox "I need a positive number"
    Exit Sub
    Case Is > 0
        MsgBox "Good work!"
        [MyField] = myvar
        RunCommand acCmdSaveRecord
        Me.Requery
    Exit Sub
    Case Else
        MsgBox "You entered '" & myvars & "'. I don't know what to do about"
    End Select
Else
    MsgBox "A Number, please"
End If

这真的是验证InputBox的最佳方法吗?

2 个答案:

答案 0 :(得分:3)

由于myvarStringCDbl(myvar)会被隐式转换回字符串。为Select Case创建临时数字变量。

答案 1 :(得分:0)

我同意其他一些答案。想想这个代码重写(注意声明的第二个变量):

Dim myvar as String
Dim myDbl as Double

myvar = inputBox ("Input a positive number, please")

if isnumeric(myvar) then
    myDbl = cDbl(myvar)
else
    msgbox "Enter a number please"
    exit sub
end if


if mydbl <=0 then
    msgbox "I need a positive number"
else        'if mydbl > 0 then
    MsgBox "Good work!"
    [MyField] = myvar
    RunCommand acCmdSaveRecord
    Me.Requery
end if

这可以通过计算零来解决问题,并将单独的变量声明为double。我猜想if语句而不是case。但现在想想你有两个变量。

debug.print "MyVar is a string containing: " & myvar

debug.print cstr(cdbl(myvar)*2)    
'This forces myvar into a double(a number-type) to do math on it and then print it out

但是,如果您要重新运行第一个打印,您会看到myvar仍然是一个字符串,可以像字符串一样使用。在VBA中,与其他语言不同,变量只是您声明的变量。如果要将它们用作其他内容,则必须声明所需类型的另一个变量。

TL; DR将它们视为不同的容器。字符串是圆框,双字节是方框。他们可能能够容纳类似的东​​西,但容器的功能受其形状的限制。在VBA中,你无法将圆圈强制成方形,因此你必须制作一个完整的第二个容器并将其转移。