To set your NumberFormat to have Leading Zeros in VBA, you can use Range.NumberFormat="0…0" So, 4 zeros would beRange.NumberFormat="0000", 5 zeros would beRange.NumberFormat="00000", etc.
To dynamically create the correct number of zeros, we can use the String function. For example, Range.NumberFormat = String(4, "0") for 4 zeroes, or Range.NumberFormat = String(5, "0") for 5 zeroes.
To count the maximum length of text in a range, we can use the SUMPRODUCT, MAX, and LEN Worksheet Functions: =SUMPRODUCT(MAX(LEN(A:A))). To ensure that this is always at least 4, we include 4 in the MAX: =SUMPRODUCT(MAX(4, LEN(A:A))).
To use that in VBA, we can pass it to the Evaluate function of the Worksheet. For example, if the column is in Sheet1, then you can use Sheet1.Evaluate("SUMPRODUCT(MAX(4, LEN(A:A)))") to get the maximum length of that column. (If you have headers, you might need to specify your data more exactly than just A:A for the entire column — or ensure that the header is 4 characters or fewer!)
And, combining everything into a neat little bit of code for a Range:
'Define Range however you want
Dim Target AS Range
Set Target = Sheet1.Columns(1)
'Set the NumberFormat
With Target
.NumberFormat = String(.Worksheet.Evaluate("SUMPRODUCT(MAX(4,LEN(" & .Address() & ")))"), "0")
End With