Loop through range, Autofit height

J

John

This is a sub I made to loop through a range and autofit row height of each
row:

Sub AutoHeight()
Dim c As Range
For Each c In Sheet1.Range("AutoFit")
Rows.AutoFit
Next c
End Sub

The macro just keeps running and running. What;'s wrong with my sub?
 
J

JLGWhiz

What are your parameters for the range named "AutoFit", which, by the way,
is a bad practice to use reserved words for names and variables.
 
R

RB Smissaert

Firstly, make sure you always have Option Explicit at the top of every
module and form.
You will see why when you try to run the code you posted with that done.

Then try code like this:

Sub AutoHeight()

Dim r As Long

With Sheets("Sheet1").Range("AutoFit")
For r = 1 To .Rows.Count
.Rows(r).AutoFit
Next r
End With

End Sub


RBS
 
J

JLGWhiz

This might work better if the named range is defined.

Sub AutoHeight()
Sheets("Sheet1".Range("AutoFit").Rows.AutoFit
End Sub
 
R

RB Smissaert

Sheets("Sheet1".Range("AutoFit").Rows.AutoFit

Ah, yes, of course no need for the loop as I posted.

RBS
 
J

JLGWhiz

works even better with the parentheses in place:

Sub AutoHeight()
Sheets("Sheet1").Range("AutoFit").Rows.AutoFit
End Sub
 
R

RB Smissaert

Ah, yes, infinite better!

RBS


JLGWhiz said:
works even better with the parentheses in place:

Sub AutoHeight()
Sheets("Sheet1").Range("AutoFit").Rows.AutoFit
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top