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.
1 Answer 1
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)