Trouble with leading 0s in VBA

mtterry

New Member
Joined
Aug 9, 2016
Messages
45
I have a column with unique IDs that are supposed to be 7 characters in length. Sometimes when these get manually input the leading 0 is omitted, so I was writing a macro to check, and if the number of characters is 6, to add a 0 to the beginning. In some instances these cells are formatted as Text, in other cases as 'Custom'. To get everything on the same page, I inserted a step that formats them all to Text. When this step occurs, it strips the leading 0 from those cells that were formatted as Custom, then when the rest of the macro runs to check the length of the text string, it is only entering a 0 on a few select cases, not to every cell that appears to only have 6 characters. I'm not sure why this is happening, below is a snapshot of the code that I'm using. The line that highlights the cell was only meant to catch rare instances where someone made a bigger error and perhaps forgot an additional number.

Dim cel As range

Columns("A:A").Select
Selection.NumberFormat = "@"

For Each cel in Range("A1", Range("A" & Rows.Count).End(xlUp))
If Len(cel.Value) = 6 Then cel.Value = "0" & cel.Value
If Len(cel.Value) <> 7 Then cel.Interior.ColorIndex = 6
Next
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
How about

Code:
For Each Cel in Range("A1", Range("A" & Rows.Count).End(xlUp))
    cel.Value = "'" & Right("0000000" & cel.Text, 7)
Next
 
Last edited:
Upvote 0
Here is another way that avoids looping through each cell...
Code:
[table="width: 500"]
[tr]
	[td]With Range("A1", Range("A" & Rows.Count).End(xlUp))
  .Value = Evaluate("IF({1},TEXT(" & .Address & ",""'0000000""))")
End With[/td]
[/tr]
[/table]
 
Upvote 0

Forum statistics

Threads
1,223,908
Messages
6,175,304
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top