Avoid For Each Loop

daniel22bg

New Member
Joined
Nov 21, 2008
Messages
31
Hi There,

I have a range of about 500 cells, some of which are empty and others are numbers. I would like to divide all the numbers with VBA by 100 without affecting the empty cells. Now i have the following Loop, which takes awfully lot of time. Can I avoid these loops somehow, so that I can optimize my code? Thanks a lot :)
Code:
Dim Rng As Range               
 
For Each Rng In Sheets("1").Range("A1:A500"))
          If Not (IsEmpty(Rng)) Then
                 Rng.Value = Rng.Value / 100
          End If
Next Rng
 

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
I'm sure there's a better answer, but multiplying by .01 should be faster than dividing by 100. Division is one of the slower of the math functions in programming.

And then you can get rid of the IsEmpty test.
 
Upvote 0
Hi

The PasteSpecial method and the SpecialCells method are what you need:

Code:
Dim r As Range

'first write 100 into an empty cell:

Cells(1,"IV").Value = 100
Cells(1,"IV").Copy

On Error Resume Next
Set r = Sheets("1").Range("A1:A500").SpecialCells(xlCellTypeConstants,xlNumbers)
On Error Goto 0
If Not r Is Nothing Then
  r.PasteSpecial xlPasteValues,xlPasteSpecialOperationDivide
Else
  'no number found - do something else
End if

'clean up:
Cells(1,"IV").Clear
 
Upvote 0

Forum statistics

Threads
1,214,527
Messages
6,120,058
Members
448,940
Latest member
mdusw

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