megagosha
megagosha

Reputation: 23

Excel VBA code how to add text to specific cell

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?

Upvotes: 0

Views: 4084

Answers (2)

Benno Grimm
Benno Grimm

Reputation: 530

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.

Upvotes: 1

Gary's Student
Gary's Student

Reputation: 96753

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.

Upvotes: 0

Related Questions