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

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
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,224,823
Messages
6,181,184
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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