Question

This is my first question on the forum, but reading previous questions has been enormously helpful in the project I'm working on, so already my thanks. I couldn't find an answer to this, but apologies if I overlooked something.

I am writing an excel macro in vba, and am trying to create a select case... statement in which the expression has a variable boolean and numeric component. For example, the macro can pull "> 3" or "< 3" from another worksheet.

My hope had been that I could assign to a string all of these parameters, i.e.:

test1 = "is " & BoolOperator1 & " " & NumericValue1

and then

Select case ValuetoCompare
    Case test1
      'Do something
    Case test2
       '...

Is there a way to do this? I suppose the alternative would be to nest the case with the numeric variable inside a select function that determines the operator, but I thought this would be more elegant.

Thanks in advance for your guidance--

Josh

Was it helpful?

Solution

Assuming that you'll get a string BoolOperator1 that is a valid operator, e.g. >=, =, and a numeric value NumericValue1, the easiest way to execute this comparison on another numeric value ValueToCompare is to use the Evaluate function. This will execute a string as VBA and return it's result.

In your case, you could simply use:

If Evaluate(ValueToCompare&BoolOperator1&NumericValue1) Then ...

If you want to use this in a Select Case statement, you'd either need to use a simple If ... ElseIf ... statement - or use this trick:

Select Case True
    Case Evaluate(ValueToCompare&BoolOperator1&NumericValue1): ...
    Case Evaluate(ValueToCompare&BoolOperator2&NumericValue2): ...
    Case Else ...
End Select
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top