views:

109

answers:

3

I'm writing a function that requires input and my data validation looks very awkward. If InputFld isn't "A","B", or "C", then it's an error:

If InputFld <>"A" and InputFld<>"B" and InputFld<>"C" then goto ErrorHandler

This just looks ugly to me. Is there a more elegant solution? I'd like to just write something like:

If InputFld not in ("A","B","C") then goto ErrorHandler

See? Much easier to read and maintain this way. But I don't know how to do it.

+1  A: 

Eval() should allow you to do something similar. This expression returns -1 (True):

Debug.Print Eval("""g"" Not In (""a"",""b"",""c"")")

I wouldn't call that elegant, though.

Consider using the Like operator. This expression returns True:

Debug.Print Not "g" Like "[abc]"
HansUp
+1. It's not much better, but I didn't know you could use brackets like that. Learned something new.
PowerUser
Downvoter, care to explain?
HansUp
+2  A: 

At least two ways to do that:

public function IsInSet(byval value as variant, paramarray theset() as variant) as boolean
  dim i as long 

  for i=lbound(theset) to ubound(theset)
    if value = theset(i) then
      isinset = true
      exit function
    end if
  next
end function

Usage: If not IsInSet(val, "A", "B", "C") then ...


public function IsInSet(byval value as variant, theset as variant) as boolean
  dim i as long 

  for i=lbound(theset) to ubound(theset)
    if value = theset(i) then
      isinset = true
      exit function
    end if
  next  
end function

Usage: If not IsInSet(val, array("A", "B", "C")) then ...

GSerg
+1 for teaching me about paramarrays. Didn't know those existed.
PowerUser
This is one of those functions that you'd think would be automatically included in the VBA API. I'll probably have this question again, so I'm adding your code to my utility library. Thanks!
PowerUser
+5  A: 

How about:

If Instr("ABC",InputFld)=0 Then
Remou
PowerUser
The other answers remind me of a Monty Python skit where they go mosquito hunting with a bazooka.
Jeff O