Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - Performing function to each cells in range

Tags:

range

excel

vba

Let's say I have a range called rng1

Set rng1 = Worksheets("Sheet1").Range("A1","A5")

Is there a quick and easy way to perform a mathematical function, lets say divide all those cell values by 2, for all the cells in rng1?

Any help is appreciated!

like image 221
user1130306 Avatar asked Jan 16 '12 19:01

user1130306


1 Answers

It's very easy, but the final code will depend on where you want to store the new values. For example, if you want to store the values divided by 2 in the next column:

Sub test()

Dim cell As Range

For Each cell In Range("A1:A5")
    cell.Offset(, 1).Value = cell.Value / 2
Next

End Sub

Mind you there are more efficient ways to do this than using offset if your range is large, but for a smaller range, this is totally acceptable and fast.

If you want to overwrite the values, you can simply use cell.Value in place of cell.Offset(,1).Value

like image 154
aevanko Avatar answered Sep 23 '22 04:09

aevanko