0

I know this question has been asked a hundred times on here, for example:

but I just can't get my code to work. I am trying to do a simple if/then statement in field calculator. I have a column (risk_value) I want to populate based on the values in the other (risk_color). There are only four values in Risk_color: Green, yellow, red, null.

enter image description here

I tried writing code in VBA:

Pre-logic script Code:

Dim val
If [RISK_COLOR] = "Green" Then     
     val = "Low"
elseif [RISK_COLOR] = "Yellow" Then     
     val = "Medium"
elseif [RISK_COLOR] = "Red" Then     
     val = "High"
elseif [RISK_COLOR] = "<Null>" Then     
     val = "<Null>"
end if

RISK_VALUE=

val

enter image description here

Error executing function.

Then I tried python string:

def Value(color):
    if (color == 'Green'):
        return "Low"
    elif (color == 'Yellow'):
        return "Medium"
    elif (color == 'Red'):
        return "High"
    else:
        return "<Null>"

RISK_VALUE=Value(!RISK_COLOR!)

enter image description here

Error executing function.

What am I doing wrong?

  • 2
    Double single quotes after Red in your Python code – Bjorn Jan 24 at 14:49
  • For the VBA code you should remove the Dim val at start. Also you have to check if your <null> value are really text (you seem to assume that in your code), if not they are null value and you should handle them differently – J.R Jan 24 at 14:50
  • @Bjorn I see it one single quote after 'Red'', but good catch. – ahmadhanb Jan 24 at 14:52
  • If this question has been asked a hundred times before I think you should provide a link to at least one of those Q&As so that we can try to understand whether it needs to be improved/closed. We seek to only have useful Q&As on this site. – PolyGeo Jan 24 at 19:21
2

It is how you are dealing with Null values. You are treating Null as a string when it is NOTHING! How can nothing be something?

But now think about what you are asking, in your case if colour is not green, yellow or red then it can only be a Null value. So you don't need to test if it is Null as you have already checked all other options.

So your VB script code need only be:

Dim val
If [RISK_COLOR] = "Green" Then     
     val = "Low"
elseif [RISK_COLOR] = "Yellow" Then     
     val = "Medium"
elseif [RISK_COLOR] = "Red" Then     
     val = "High"
else    
     val = "<Null>"
end if

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.