0

How do I pass a variable name - as the variable, not its name as a string - in a VB codeblock when calculating a field in ArcPy?

I am using field calculator in a tool I built with Model Builder to replace null values in one field of a feature class with 0, using a VB code block. It works as expected when I run the tool.

The field name is a string variable: Count_DATE where I update DATE in the field name daily.

When I export and run the tool from a Python script, there's an issue with the variable of the field name in the VB codeblock.

Count_DATE = "Count_DATE"
fc = Count_by_area
arcpy.CalculateField_management(fc, "%Count_DATE%", "Output", "VB", "If IsNull([%Count_DATE%]) Then Output = 0 Else Output = [%Count_DATE%] End If ")

I tried removing the % and [] but am not sure how to deal with the entire code block being within quotation marks.

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Jul 9, 2020 at 15:26

1 Answer 1

0

You can make use of string formatting in python to pass variables into strings. See Python String format() Method. Use everything as in your original VB, replacing just the field name with the str formatting placeholder {0}.

Count_DATE = "Count_DATE"
fc = Count_by_area
vb_string = "If IsNull([{0}]) Then Output = 0 Else Output = [{0}] End If".format(Count_Date)
arcpy.CalculateField_management(fc, "%Count_DATE%", "Output", "VB", vb_string)

The {0} is a placeholder for your variable Count_Date, which you pass from the .format(). If you had multiple variables to pass you just include them - "First variable {0}, Second {1}, Third {2}".format(varone, vartwo, varthree)

(and you can include it all in your arcpy.CalculateField() line, rather as a separate variable vb_string - it's just easier to see when it's separate and passed as a variable)

For readability (or for syntax if you have, say, python in your string instead of VB) you can also use triple quotes around your string, which will allow you to have a multiline string, and indents etc..

vb_string = """
If IsNull([{0}]) Then
 Output = 0 
Else
 Output = [{0}] 
End If
""".format(Count_Date)
answered Jul 9, 2020 at 15:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.