10101
10101

Reputation: 2402

Multiple if statements for multiple values

This question has been asked probably million times, but I must be doing something wrong as my logical code does not work correct and I can't understand why.

I have two conditions:

  1. oObjectSearchResults.Count = 0
  2. ThisWorkbook.Worksheets("Data").Range("Z2").Value = "1"

I need it work like:

IF oObjectSearchResults.Count = 0 and ThisWorkbook.Worksheets("Data").Range("Z2").Value = ""

Then Do process

IF oObjectSearchResults.Count = 1 and ThisWorkbook.Worksheets("Data").Range("Z2").Value = "1"

Then Do process

Else Msgbox ("There is already file with name blabla, use already existing one")

Here is my code:

If oObjectSearchResults.Count = 0 And ThisWorkbook.Worksheets("Data").Range("Z2").Value = "" Then
'Do process
If oObjectSearchResults.Count = 1 And ThisWorkbook.Worksheets("Data").Range("Z2").Value = "1" Then
'Do process
Else
Msgbox ("There is already file with name blabla, use already existing one")
End If
End If 

Upvotes: 0

Views: 58

Answers (2)

Tim Baverstock
Tim Baverstock

Reputation: 568

It might have helped you debug it if you'd used a debugger or added logging to show which outcomes were triggered by given conditions. From your code, I'm guessing condition 1 would have printed 'Doing 1' and 'Doing else', whereas condition 2 would have printed nothing at all.

I think your code needs this structure:

 if condition 1 then
   outcome 1
 else
   if condition 2 then
      outcome 2
   else
      something else
   endif
 endif

Some languages allow you to merge 'else' and 'if' to avoid excessive indentation and a flotilla of 'endif's at the end - you just need one.

It can also help - where you have 'and's in conditions, to have two nested 'if's:

if condition1A
    if condition1B
       operation 1
    endif
endif

is equivalent to

if condition1A AND condition1B
   operation 1
endif

except that you can add logging statements (print, alert, whatever) to show that condition1A has succeeded but condition1B perhaps hasn't.

If you have 'or's in your conditions, it's rarely necessary to log them separately.

Upvotes: 2

bajun65537
bajun65537

Reputation: 543

If I understand your logic correctly, you should try it like this:

If oObjectSearchResults.Count = 0 And ThisWorkbook.Worksheets("Data").Range("Z2").Value = "" Then
'Do process
ElseIf oObjectSearchResults.Count = 1 And ThisWorkbook.Worksheets("Data").Range("Z2").Value = "1" Then
'Do process
Else
Msgbox ("There is already file with name blabla, use already existing one")
End If

Upvotes: 1

Related Questions