Looping through a range object modifying each cell

tcardwell

Board Regular
Joined
Dec 22, 2013
Messages
86
Trying to create a subroutine that takes a selected range and loops through each cell trimming off all but the first five characters. Current code is as follows:

Sub TrimAcntNo()

Dim Cell As Range
For Each Cell In Selection
ActiveCell.Formula = "=Left(activecell,5)"
Next Cell
End Sub

I am getting a #Name error message when I run this code.
Just trying to run through the cells and trim off all but the first 5 characters.

TIA,
tcardwell
 

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.
You had the right idea.
Code:
Dim c As Range
For Each c In Selection
c = Left(c,5)
Next
End Sub
 
Upvote 0
Try:
Code:
Sub TrimAcntNo()
    Dim Cell As Range
    For Each Cell In Selection
        ActiveCell = Left(ActiveCell, 5)
    Next Cell
End Sub
 
Upvote 0
Maybe you need...

Code:
Sub TrimAcntNo()
Dim Cell As Range
For Each Cell In Selection
Cell.Value = Left(Cell, 5)
Next Cell
End Sub
 
Upvote 0
For the collection:
Rich (BB code):
Sub Left5()
  Selection.Value = Evaluate("LEFT(" & Selection.Address & ",5)")
End Sub
 
Upvote 0
Assuming your data is in column A starting in row 2, try:
Code:
Sub TrimAcntNo()
    Dim LastRow As Long
    LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Dim Cell As Range
    For Each Cell In Range("A2:A" & LastRow)
        Cell = Left(Cell, 5)
    Next Cell
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,908
Messages
6,175,306
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

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.
Go back
Back
Top