Simple If - Then - Else Programming

02-16-2014 11:27 AM
New Contributor
Could someone please advise me how do use a simple "if - then - else" construct to take two columns of population data on different dates and compute a new column of the percentage change?  I also need to account for potential divide-by-zero errors.  I have tried writing straightforward
if field1 > 0 then
    (field2 - field1)/field1
end if (done both with and without the end if)
but of course this fails.  I tried using the example code from one of the knowledgebase articles:
Static lastValue as variant
Dim Output As Double

If IsEmpty(lastValue) Then
Output = 0
Output = (([Increment] - lastValue) / lastValue) * 100
End If
lastValue = [Increment]
but this, too fails.  I had even created a field containing the "increment" (but named differently), but with no success.  And of course the compiler gives absolutely no idea of what might be wrong.

This should NOT be that hard.  What am I doing wrong?
0 Kudos
2 Replies
MVP Emeritus
If you want to use the Python parser see the Nested Conditional Operators for some suggestions
0 Kudos
Occasional Contributor III
I am assuming you are just using field calculator.   I just threw together a shapefile to test your script with three fields [pop_2000], [pop_2010], and [pct_change].  You right click on the pct_change field to run field calculator, check the Show Codeblock box, enter just the word Output in the Codeblock box, and then you can do something basic like this in the Pre-Logic Script Code box:
If IsEmpty([pop_2000]) or IsEmpty([pop_2010]) Then
     Output = -9999
     Output = (([pop_2010] - [pop_2000]) / [pop_2000]) * 100
End If

I don't even bother with dim statements because it does not care.  You can also use IsNull if you so desire.  I originally had set the Output to NULL if one of the populations was empty but it would not accept it so I used -9999 to show it was invalid.  Always make sure you put column names in square brackets, and if for some odd reason one of your columns is a string, you may have to use the val function to convert it to a number.
0 Kudos