excel exit for each loop

John Steel

New Member
Joined
Feb 7, 2017
Messages
12
Good day everyone,

I have a simple code I'm using to trim leading/trailing spaces from two ranges and I would like to exit the loop when it encounters a blank entry in those ranges. Most often only 1-3 rows of the range are populated with data and I don't need the loop running unnecessarily through blank cells.

My code is as follows.

Dim cell As Range, areaToTrim As Range 'This trims off leading and trailing spaces in the address and zoning columns from the MLS data dump on the File Information Sheet
Set areaToTrim = Sheet1.Range("B28:B57", "Bk28:BK57")
For Each cell In areaToTrim
cell.Value = Trim(cell.Value)
Next cell

I've tried inserting the following after line 3 but it doesn't accomplish what I want

If cell.Value = "" Then Exit For

Any suggestions would be appreciated.

Thanks
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
62,383
Office Version
  1. 365
Platform
  1. Windows
How about
VBA Code:
Dim cell As Range, areaToTrim As Range 'This trims off leading and trailing spaces in the address and zoning columns from the MLS data dump on the File Information Sheet
Set areaToTrim = Sheet1.Range("B28:B57", "Bk28:BK57").SpecialCells(xlConstants)
For Each cell In areaToTrim
   cell.Value = Trim(cell.Value)
Next cell
 
Solution

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
62,383
Office Version
  1. 365
Platform
  1. Windows
You're welcome & thanks for the feedback.
 

Forum statistics

Threads
1,141,302
Messages
5,705,584
Members
421,400
Latest member
chakam

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
Top