I'd like my code to find any number in column A which starts with 3 (example 300049588007) and format it to add a 0 before the number (example 0300049588007). How can I do this?
'Adding two columns
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B2").Select
'Copy text from A into B (Assignment Number Header)
Range("A1").Select
Selection.Copy
Range("B1").Select
ActiveSheet.Paste
'Edit Assingment number - inserting the formula
'Colum B
You should be able to consolidate that code substantially to make it easier.
For example:
Code:
Sub CommandButton1_Click()
Dim r As Range, rAll As Range
With Sheet1
Set rAll = Range(Cells(1, 1), Cells(2, 1).End(xlDown))
For Each r In rAll
If Left(r, 1) = "7" Then
r = "3" & r
End If
Next
End With
End Sub
One more comment - the code I provided is written to update values starting with a 7 with a 3 in front of it.
The below code is what you were trying for:
Code:
Sub CommandButton1_Click()
Dim r As Range, rAll As Range
With Sheet1
Set rAll = Range(Cells(1, 1), Cells(2, 1).End(xlDown))
For Each r In rAll
If Left(r, 1) = "3" Then
r = "0" & r
End If
Next
End With
End Sub
Also - since Excel automatically removes leading zeros, you will need to ensure whatever column you are working in is formatted as "Text" so the zeros show.
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.