Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - Copy first three characters from string into another cell

Tags:

excel

vba

I struggle with splitting the first three characters from a cell and insert them into another cell as a seperate string.

My (example) input:

A

A123456
A133457
B123456
B133457
...

What I want:

A            B
A123456      A12
A133457      A13
B123456      B12
B133457      B13
...          ...

What I tried:

Dim ws As Worksheet
Dim cell As Range

Set ws = Worksheets("summary")

For Each cell In ws.Range("A").Cells
    cell.Value = Left(cell.Value, 3)
    Next cell

This can't work since I'd overwrite the value in all the cells A which I don't want to. Can someone provide help?

like image 848
KevinD Avatar asked Feb 16 '16 11:02

KevinD


1 Answers

in Excel without VBA, you can use formula: =LEFT(A1,3)

With VBA, you can do the following:

For Each cell In ws.Range("A:A").Cells
    cell.Offset(0, 1).Value = Left(cell.Value, 3)
Next cell

Note that I have amended the range. You probably want to limit is further as "A:A" will take a while.

The offset function says "use the cell 1 to the right of the current cell".

like image 139
GinjaNinja Avatar answered Sep 20 '22 08:09

GinjaNinja