Combine And Statement

kitty77

Registered User.
Local time
Today, 06:29
Joined
May 27, 2019
Messages
715
How do I combine these into one statement? I'm getting a type mismatch error.

If [Mtest].Enabled = True Then [Mexam4] = [Msample1] & ".PDF" And [Mexam5] = [Msample2] & ".PDF"
 
Code:
if [Mtest].Enabled   Then
  [Mexam4] = [Msample1] & ".PDF"
  [Mexam5] = [Msample2] & ".PDF"
endif
 
Got it. Is there a way to combine it on one line? With And?
 
Yes, but why would you want to? It makes the code much less readable. Professionals would never do that since it makes the first statement "disappear" as they are reading the code.
 
Technically you could remove the line breaks and tabs and get it on one line. But it is not possible to do it in fewer (non return/tab/space) characters than Ranman has done.

Don't let me down master coders--prove me wrong in the posts below.
 
I see... Would it look like without the returns and breaks?
 
I'm going to guess the syntax would look like this:

if [Mtest].Enabled Then : [Mexam4] = [Msample1] & ".PDF": [Mexam5] = [Msample2] & ".PDF": endif

But I could be wrong. Even if I'm right - DO NOT USE THIS CODE.
 
The correct syntax omits one of the colons Pat offered. I believe the colon following "Then" would cause an issue.

Code:
If [Mtest].Enabled Then [Mexam4] = [Msample1] & ".PDF" : [Mexam5] = [Msample2] & ".PDF" : endif

Oddly enough, though it might be legal and thus would be accepted, there does not appear to be a requirement for an EndIf at the end of the multi-clause IF statement. It is POSSIBLE that the EndIf would cause an error. And, in fact, if this statement were embedded inside an outer IF-block type of statement, it might prematurely terminate the outer block. By using the IF-block structure you would make the block structure absolutely unambiguous and thus make it much easier to read.

My source for syntax discussions is the MS VBA Language Reference, v20140424, released Apr 30, 2014, sections 5.4.2.8 (IF statement) and 5.4.2.9 (Single-Line IF statement). The distinction is that if you have an EndOfLine character after the Then keyword, you have a IF-block whereas if you don't have the EOL then you have an IF-Statement. The IF-block absolutely requires the EndIf.

Having chimed in, I have to agree with Pat that it is unwise to use that in-line structure because it obfuscates what you are doing.
Syntactically there is no need for a single-line statement or a statement group. The IF-block is unmistakable and thus would be preferred for reasons of clarity.
 
Code:
[Mexam4] = IIf([Mtest].Enabled, [Msample1], [Msample2]) & ".PDF"
 
If that's a submission for my contest, you're in last place so far.
 

Users who are viewing this thread

Back
Top Bottom