When running this code -->

Private Sub cmdSquare_Click()
    Dim i
    i = InputBox("Please enter a number.", "Input Box")
    MsgBox "The square of " & i & " is " & (i ^ 2), vbOKOnly, "Result"
    MsgBox "The square root of " & i & " is " & Sqr(i), vbOKOnly, "Result"
End Sub

if I click on the 'Cancel' button in the "Please enter a number" Input Box I get a Run-time error "13": type mismatch error. When I click on debug the red text above is hightlighted. What does that mean and how can I fix it so that I do not get that error?

Recommended Answers

All 2 Replies

Private Sub cmdSquare_Click()
    Dim i
    i = InputBox("Please enter a number.", "Input Box")
    MsgBox "The square of " & i & " is " & (i ^ 2), vbOKOnly, "Result"
    MsgBox "The square root of " & i & " is " & Sqr(i), vbOKOnly, "Result"
End Sub

The issue comes from the variable i having no value (null), so you have a couple options:

1.) Create a default value to pass through the math equation:

Private Sub cmdSquare_Click()
    Dim i
    Dim intDefaultValue as Integer
    intDefaultValue = 10
    i = InputBox("Please enter a number.", "Input Box")
    if i is "" then i = intDefaultValue
    MsgBox "The square of " & i & " is " & (i ^ 2), vbOKOnly, "Result"
    MsgBox "The square root of " & i & " is " & Sqr(i), vbOKOnly, "Result"
End Sub

2.) Create a loop until the user enters a number:

Private Sub cmdSquare_Click()
      Dim i
    Do until i <> "" and isNumeric(i)
        i = InputBox("Please enter a number.", "Input Box")
    Loop
    if isNumeric(i) then  
   	MsgBox "The square of " & i & " is " & (i ^ 2), vbOKOnly, "Result"
    	MsgBox "The square root of " & i & " is " & Sqr(i), vbOKOnly, "Result"
    End If
End Sub

Either way you slice you need to also check to make sure the entered value from the user is of the correct type, an integer.... You can use the isNumeric function.

HTH's
sinnerFA

I had a coded change but could then not find your post; but what I added was a test to check if i ="" and if so exit the program. Hope that helps as I did not save my code. makybe

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.