2

im only new to vba so i dont really know much about programming, anyway, i created a macro that adds a zero before a single digit string number in my selection, it only works if my selections are single digits only but doesn't work when theres a double digits or more in my selection, this is my code:

Sub AddZero()
 Dim cell As Range
 
 For Each cell In Selection
  If Not IsNumeric(cell) = False And cell > 10 Then
   Exit Sub
    Else:
   cell = "0" & cell
  End If
 Next
End Sub

How can i make my macro skip all cells with double digits and only target single digits, pls help and thanks very much in advance.

2
  • Flip the logic and don't Exit Sub from the loop.If IsNumeric(cell) And cell < 10 Then cell.Value = "0" & cell.Value Commented Mar 26, 2021 at 4:13
  • Ohhhhhhhh, it works!!, thanks very much sir Tim, Commented Mar 26, 2021 at 4:16

1 Answer 1

2

How can i make my macro skip all cells with double digits and only target single digits

No need for a Loop. You can achieve what you are doing in 1 line

Selection.NumberFormat = "00"

Also avoid the use of Selection. Try something like this

Sub AddZero()
    Dim rng As Range
    
    '~~> Change this to the relevant sheet/range
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A10")
    
    rng.NumberFormat = "00"
End Sub

BEFORE

enter image description here

AFTER

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Dhanyavaad Tiwariji _/|\_ :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.