VBA nested if

MartinL

Well-known Member
Joined
Oct 16, 2008
Messages
1,141
Office Version
  1. 365
Platform
  1. Windows
Hi can I rewite this better?

Code:
If Flag = True Then _
            If vCode <> "" Then _
                If lCodeV >= 0 Then _
                    lCodeVTemp = 0
                    
 If Flag = True Then _
            If vCode <> "" Then _
                If lCodeV < 0 Then _
                    lCodeVTemp = lCodeV
why can i not put:
Code:
If Flag = True And vCode <> "" and lCodeV >= 0 Then _
      lCodeVTemp = 0
ElseIf Flag = True And vCode <> "" and lCodeV < 0 Then _
      lCodeVTemp = lCodeV
EndIf
I get error message "else without if"
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Try removing the continuation characters (_)

Code:
If Flag = True And vCode <> "" And lCodeV >= 0 Then
      lCodeVTemp = 0
ElseIf Flag = True And vCode <> "" And lCodeV < 0 Then
      lCodeVTemp = lCodeV
End If
 
Upvote 0
Hi Martin,

You need to lose the line continuation characters highlighted in red:
Rich (BB code):
If Flag = True And vCode <> "" and lCodeV >= 0 Then _
      lCodeVTemp = 0
ElseIf Flag = True And vCode <> "" and lCodeV < 0 Then _
      lCodeVTemp = lCodeV
EndIf


Or, here's another way of writing it:
Rich (BB code):
    If Flag Then
        If vCode <> "" Then
            If lCodeV >= 0 Then
                lCodeVTemp = 0
            Else
                lCodeVTemp = lCodeV
            End If
        End If
    End If

Hope that helps...
 
Upvote 0
You can also change it to two separate single line IFs
Code:
If Flag = True And vCode <> "" and lCodeV >= 0 Then _
      lCodeVTemp = 0
If Flag = True And vCode <> "" and lCodeV < 0 Then _
      lCodeVTemp = lCodeV
 
Upvote 0

Forum statistics

Threads
1,213,538
Messages
6,114,218
Members
448,554
Latest member
Gleisner2

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top