Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Math Operator from InputBox

Tags:

excel

vba

I am trying to use InputBox to get a math operator

E.g.: +. When I replace the operator with the variable it gives an error

Expected Then or GoTo

This doesn't work:

Sub NumTest()
Dim Val As Integer

Val = Application.InputBox("Value", "Value", Type:=1)
oper = Application.InputBox("Op")
rcell = Range("D2")

If rcell oper Val = True Then
    MsgBox "True"
End If
End Sub

This does work:

Sub NumTest()
Dim Val As Integer

Val = Application.InputBox("Value", "Value", Type:=1)
oper = Application.InputBox("Op")
rcell = Range("D2")

If rcell > Val = True Then
    MsgBox "True"
End If
End Sub
like image 972
FreeSoftwareServers Avatar asked Mar 03 '26 23:03

FreeSoftwareServers


1 Answers

Create a string and use Application.Evaluate:

Sub NumTest()
    Dim Val As Integer
    Val = Application.InputBox("Value", "Value", Type:=1)
    Dim oper As String
    oper = Application.InputBox("Op")
    Dim rcell As String
    rcell = ActiveSheet.Range("D2")

    If Application.Evaluate(rcell & oper & Val) Then
        MsgBox "True"
    Else
        MsgBox "False"
    End If
End Sub
like image 71
Scott Craner Avatar answered Mar 06 '26 13:03

Scott Craner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!