0

我目前正在尝试编写一个基于 USB 设备序列号与 USB 设备接口的程序。我让它部分工作,这样它就可以在文本框中接受正确的序列号,但是如果将除整数之外的任何东西放入框中,它将抛出错误。我怎样才能解决这个问题?到目前为止,我试图解决这个问题一直没有成功。简而言之,我希望程序从文本框中读取 5 位序列号并尝试连接,如果添加了除整数以外的任何内容,它只会向用户抛出一条消息,说明序列号不正确。这是我到目前为止所拥有的。

'Declares an integer to be used for custom serial numbers incase phidgets need to be swapped.
    Dim MC1Serial As Integer
    'Throws error if there's no real serial in the corresponding box.
    If TextSerial1.Text = 0 Then
        MsgBox("Please ensure you have a proper serial numbers in the textbox, and not 0")
    Else
        MC1Serial = TextSerial1.Text
    End If
    'Creates a new instance of a MC for the first controller.
    MC1 = New Phidget21COM.PhidgetMotorControl
    'Attempts to attach phidget and either checks the box or throws an error.
    MC1.Open(MC1Serial)
    MC1.WaitForAttachment(1000)
    If MC1.IsAttached = True Then
        CheckMC1.Checked = True
        'Enables the timer to allow the position of the buttons to update accordingly.
        TimerJoysticks.Enabled = True
    Else
        MsgBox("There was a problem finding MC1. Check connections and settings.")
    End If
4

1 回答 1

1

你可以做很多事情。Val 函数就是其中之一。您还可以使用IsNumeric检查整个输入字符串是否实际上是一个数字。

If Not IsNumeric(TextSerial1.Text) or Val(TextSerial1.Text) = 0 Then
    MsgBox("Please ensure you have a proper serial numbers in the textbox, and not 0")
    ' You should exit the sub here so that the code doesn't continue.

Else
    MC1Serial = CInt(TextSerial1.Text)
End If
于 2013-02-10T15:36:12.917 回答