VBA Conditional Stmt Question (IN operator)

J

jhrBanker

I'm trying to check for multiple values in an IF statement in vba, but I'm
receiving error messages:
If Mid(InputString, 54, 3) IN('070', '111', '305', '345', '456') Then
Statement1
Else
Statement2
End If

I've tried double-quotes in place of single-quotes, but that didn't work.
Any help will be appreciated.
 
S

Svetlana

You should make it like this:
If Mid(InputString, 54, 3)="070" Or Mid(InputString, 54, 3)=111 Or
etc.. Then
Statement1
Else
Statement2
End If
 
S

Stefan Hoffmann

hi,
I'm trying to check for multiple values in an IF statement in vba, but I'm
receiving error messages:
If Mid(InputString, 54, 3) IN('070', '111', '305', '345', '456') Then
Statement1
Else
Statement2
End If
You can also use

Select Case Mid(InputString, 54, 3)
Case "070", "111", "305", "345", "456"
Statement1
Case Else
Statement2
End Select


mfG
--> stefan <--
 
K

Klatuu

IN is an SQL predicate, not a VBA function.
This is better than a string of If Else

Select Case Mid(InputString, 54, 3)
Case "070", "111", "305", "345", "456"
Statement 1
Case Else
Statement 2
End Select
 
S

Stefan Hoffmann

hi,

JethroUK© said:
If INSTR("070,111,305,345,456", Mid(InputString, 54, 3)) Then
It's not a good idea, because it will also be True for "0,1" etc.

mfG
--> stefan <--
 
J

JethroUK©

but that will never be found - hence i included the comma seperator - i will
work perfectly
 
S

Stefan Hoffmann

hi,

JethroUK© said:
but that will never be found - hence i included the comma seperator - i will
work perfectly
You have no control over InputString, hence Mid(InputString, 54, 3) may
return "0,1", thus the false positive.


mfG
--> stefan <--
 
J

JethroUK©

there is considerably less chance of someone typing '0,1' by mistake than
typing '305' by mistake

by 'any' method they'll get the wrong result - hence i would still use:

If INSTR("070,111,305,345,456", Mid(InputString, 54, 3)) Then
 
D

Douglas J. Steele

To handle Stefan's concern, use

If INSTR(",070,111,305,345,456,", "," & Mid(InputString, 54, 3) & ",") Then
 
D

david epsom dot com dot au

'In' is only available from the expression evaluator:

If eval("Mid('" & InputString & "', 54, 3) IN('070', '111', '305', '345',
'456')") Then

CASE is a better approach.

(david)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top