忽略空文本字段

忽略空文本字段

在此处输入图片描述

在用户窗体中运行子程序时,我不断收到转换异常。它在读取时识别出空值txtMileage.text = ""并抛出错误,因为它试图确定该值是否大于 300

If btnYes.Checked = True And txtMileage.Text > 300 Then MsgBox("Distance Exceeds 300 Miles") txtMileage.Focus() Exit Sub

我需要它忽略检查值btnNo.checked = truetxtMileage.text = ""

有什么想法吗?

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles cmdCalculate.Click
    If btnNo.Checked = False And btnYes.Checked = False Then
        MsgBox("Please select yes or no")
        Exit Sub
    End If
    If btnYes.Checked = True And txtMileage.Text = "" Then
        MsgBox("Please instert Mileage")
        txtMileage.Focus()
        Exit Sub
    End If
    If btnNo.Checked = True And txtMileage.Text = "" Then

    End If
    If btnYes.Checked = True And txtMileage.Text > 300 Then
        MsgBox("Distance Exceeds 300 Miles")
        txtMileage.Focus()
        Exit Sub
    End If
End Sub

更新了错误消息,但仍然会抛出

If btnYes.Checked = True And txtMileage.Text = "" Then MsgBox("Please insert Mileage") txtMileage.Focus() Exit Sub ElseIf btnYes.Checked = True And txtMileage.Text > 300 Then MsgBox("Distance Exceeds 300 Miles") txtMileage.Focus() Exit Sub End If

ElseIf btnYes.Checked = True And txtMileage.Text > 300 Then似乎是最后一行的问题Then

答案1

如何仅检查是否.Text包含数字值,如果不包含,则将其设置为0

If Not IsNumeric(txtMileage.Text) Then txtMileage.Text = 0

您可能希望或不希望将其存储为变量以避免更改控件。

Dim txt as Variant
txt = txtMileage.Text
If Not IsNumeric(txt) Then txt  = 0

答案2

将其作为排除选项elseif。 当为空时txtMileage.Text = "",它没有机会进行检查if >300

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles cmdCalculate.Click
    If btnNo.Checked = False And btnYes.Checked = False Then
        MsgBox("Please select yes or no")
        Exit Sub
    End If
    If btnYes.Checked = True And txtMileage.Text = "" Then
        MsgBox("Please instert Mileage")
        txtMileage.Focus()
        Exit Sub
    Elseif  btnYes.Checked = True And txtMileage.Text > 300 Then
        MsgBox("Distance Exceeds 300 Miles")
        txtMileage.Focus()
        Exit Sub
    End If
    If btnNo.Checked = True And txtMileage.Text = "" Then

    End If
End Sub

相关内容