0

Length of all cells in a specific columns has to be 6 characters. If not, I have to add 0 in the beginning of each cell until cell length =6. What is the best way to do it?

4
  • 3
    Welcome to S.O! Have you tried anything? If so, please, provide the code, take a look to the tour and how to ask. Friendly reminder: StackOverflow is not a "we code for you" service provider. Introduction to VBA Commented Jul 15, 2016 at 15:04
  • Note that this can be done without VBA if you accept that the result is put in a different column. You can then hide the original column. If there is a choice, then it is almost always better to do such things with in-cell formulas than with VBA. Commented Jul 15, 2016 at 15:06
  • Yes, its even greater method. What formula should I use? Commented Jul 15, 2016 at 15:16
  • Assuming that the column you wish to reformat is in column A and starts in row 1 you could write in cell B1 the following formula and copy it down =RIGHT("000000"&MID(A1,1,6),6). Commented Jul 15, 2016 at 16:18

2 Answers 2

1
Dim lastRow As Integer
Dim i As Integer
Dim sh As Worksheet
Dim cont As String


Set sh = ThisWorkbook.Worksheets("Sheet1") 'Your Sheet

With sh
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Coloumn A

    For i = 1 To lastRow
        Cells(i, 1).NumberFormat = "@"
        Do Until Len(Cells(i, 1)) = 6   'Coloumn A
            cont = Cells(i, 1)          'Coloumn A
            Cells(i, 1) = "0" & cont    'Coloumn A
        Loop
    Next i

End With

Does this work for you? You only have to edit the coloumn that you want to check, you could use a TextBox for that.

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

Comments

0

Here is a sample for column C:

Sub Make6()
    Dim r As Range, r1 As Range, r2 As Range, r3 As Range
    bry = Array("000000", "00000", "0000", "000", "00", "0", "")
    Dim N As Long, v As String, L As Long
    Set r1 = Range("C:C")
    N = Cells(Rows.Count, "C").End(xlUp).Row
    Set r2 = Range("C1:C" & N)
    Set r3 = Range("C" & N + 1 & ":C" & Rows.Count)

    r1.NumberFormat = "@"
    For Each r In r2
        v = r.Value
        L = Len(v)
        If L < 6 Then
            r.Value = bry(L) & v
        End If
    Next r
    r3.Value = "000000"

End Sub

It will fix ALL cells in column C.

Comments

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.