Search code examples
vbaexcelmathoffice-2013

VBA return 2 variants in MsgBox


This is the start to a simple mathematical theorem demonstration.

When I run this macro neither Coefficient nor Degree appear in MsgBox.

Option Explicit
Sub Function1()
Dim Degree, Coefficient
MsgBox "Enter polynomial by terms."
Cells(1, 2).Value = Degree
Cells(2, 2).Value = Coefficient
    If IsNumeric(Degree) = True Then
    Else: MsgBox "IsNumeric(Degree)=False)"
        If IsNumeric(Coefficient) = True Then
        Else: MsgBox "IsNumeric(Coefficient)=False"
            MsgBox Coefficient & "x^" & Degree
        End If
    End If
End Sub

EDIT: new version of code as suggested by comments (still doesn't work):

Option Explicit
Sub Function1()
Dim Degree, Coefficient
MsgBox "Enter polynomial by terms."
Degree = Cells(1, 2).Value
Coefficient = Cells(2, 2).Value
    If IsNumeric(Degree) = True Then
    Else: MsgBox "IsNumeric(Degree)=False)"
        If IsNumeric(Coefficient) = True Then
        Else: MsgBox "IsNumeric(Coefficient)=False"
            MsgBox Coefficient & "x^" & Degree
        End If
    End If
End Sub

Solution

  • You may want to rewrite your procedure something like this:

    Sub Function1()
        Dim Degree, Coefficient
        MsgBox "Enter polynomial by terms."
        Degree = Cells(1, 2).Value
        Coefficient = Cells(2, 2).Value
    
        If Len(Trim(Degree)) > 0 And IsNumeric(Degree) Then
            MsgBox "Degree is numeric"
        Else
            MsgBox "Degree is not numeric. Exiting"
            Exit Sub
        End If
    
        If Len(Trim(Coefficient)) > 0 And IsNumeric(Coefficient) Then
            MsgBox "Coefficient is numeric"
        Else
            MsgBox "Coefficient is not numeric. Exiting"
            Exit Sub
        End If
    
        MsgBox Coefficient & "x^" & Degree
    
    End Sub
    

    In cell B1, type 1. In cell B2, type 2. Run the procedure and you should see expected outcome. You can build from there on.