I am trying to add FIPS codes to my county name labels and want to add either one or two zeros to the number unless it is over 100. i'm hoping someone can find the error in my code:
Function FindLabel ([Name], [FIPS])
if ([FIPS] < 10) then
FindLabel = [Name] & vbNewLine & FormatNumber (00,[FIPS])
else
if (9 < [FIPS] > 100) then
FindLabel = [Name] & vbNewLine & FormatNumber (0,[FIPS])
else
FindLabel = [Name] & vbNewLine & [FIPS]
end if
End Function
2 Answers 2
Unless you need to use vbscript, you can accomplish this in one line of python:
"{0}\n{1:03d}".format([Name], int([FIPS]))
Explanation
The curly braces reference the index position of the parameters passed to .format()
. \n
is your newline character and the :03d
bit in the second one zero pads the input so that the result is of length 3 (assuming the number isn't 3 digits already--in which case the whole number is returned.)
>>> for i in (1,7,33,98,200,123456):
print("{0} becomes {1:03d}".format(i, i))
1 becomes 001
7 becomes 007
33 becomes 033
98 becomes 098
200 becomes 200
123456 becomes 123456
If you want to use vbscript, here's an amusing approach that abuses Right()
:
Function FindLabel ([Name], [FIPS])
if [FIPS] < 1000 then
FindLabel = [Name] & vbNewLine & Right("00"&[FIPS], 3)
else
FindLabel = [Name] & vbNewLine & [FIPS]
end if
End Function
-
Thanks, Paul. How do I add a space between [Name] and [FIPS]?Chelsea Pennick McIver– Chelsea Pennick McIver2015年10月09日 20:14:18 +00:00Commented Oct 9, 2015 at 20:14
-
1Put the space instead of the \n like this. "{0} {1:03d}".format([Name], int([FIPS]))"Thomas– Thomas2015年10月09日 20:16:09 +00:00Commented Oct 9, 2015 at 20:16
-
2Well currently there is a newline (
\n
) betweenName
andFIPS
. You can change that to whatever you want.Paul– Paul2015年10月09日 20:16:20 +00:00Commented Oct 9, 2015 at 20:16
I believe the VB should look like this, but Paul's solution more elegant. This takes advantages of VB string formatting to force any number to be four digits (padding with leading zeroes if necessary).
Function FindLabel ([Name], [FIPS])
FindLabel = [NAME] & vbNewLine & Format$([FIPS],"0000")
End Function
-
FormatNumber function-- you are actually creating a string that is a whole bunch of zeroes.Paul– Paul2015年10月09日 20:21:47 +00:00Commented Oct 9, 2015 at 20:21
-
Ha, yeah OP's code is a real mess. I would use String.Format("{0:00}... anyways. Updated my answer.Thomas– Thomas2015年10月09日 20:24:10 +00:00Commented Oct 9, 2015 at 20:24
-
I can't get either of those to work. =/Paul– Paul2015年10月09日 20:30:33 +00:00Commented Oct 9, 2015 at 20:30
-
Ugh, whoops. I always forget Arc uses VBA and not VB.net. Updated.....again.Thomas– Thomas2015年10月09日 20:42:03 +00:00Commented Oct 9, 2015 at 20:42
9 < x > 100
meansx > 9
andx > 100
--- if x is greater than 100, then it is also greater than 9.else if
should be on 1 line. Not sure if that's a formatting or copy/paste issue.