WITH statement possible?

nbrcrunch

Well-known Member
Joined
Jan 1, 2003
Messages
2,062
just for kicks, I tried entering this from scratch, not even knowing if it would work. Though I later discovered that formal coding requires a little more, nonetheless, the code works.

My question is: I've read here a few times that if at all possible, avoid loops. Is there a way to achieve the end-result (trimming text values) without looping? Possibly using a WITH (object / feature) type of syntax?

Code:
Sub trimall()
For Each cell In Selection
cell.Value = Trim(cell.Value)
Next cell
End Sub
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
With faster computers nowadays this is not really an issue. Trying to change code such as yours to save a millisecond or two would be more trouble than it is worth.

This might change a bit if we have to apply that to thousands of records in a database. I never bother, even though I often have to process over 1 million records with code in Access. Putting a counter in the statusbar shows how blindingly fast things are happening, even using our outdated equipment.

You can save more run time by adding a couple of lines of code to set Calculation to Manual and Screenupdating to False and back again.

Having said that, using Copy & Paste in code rather than the equivalent loops does make a difference in running those thousands of records - but then most people would not bother with loops anyway. In this case the loops are still there, but contained in Excel code.
 
Upvote 0

Forum statistics

Threads
1,214,655
Messages
6,120,760
Members
448,991
Latest member
Hanakoro

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