Macro Works One Way But Not Other - Why?

Alex20850

Board Regular
Joined
Mar 9, 2010
Messages
146
Office Version
  1. 365
Platform
  1. Windows
The macro is to change all formulas into values:
When I run it, I get the error message if I type as it is in book, that is, with "with ActiveSheet" on same line.
However, if I have it on separate line, it works. Why is that?

Compile Error
Syntax Error with the Dim line highlighted.

Macro with Error:
Sub ChangeToValue()
Dim rng as Range with ActiveSheet
For Each rng In .UsedRange
rng.Value = rng.Value
Next rng
End With
End Sub

Macro without Error:
Sub ChangeToValue()
Dim rng as Range
with ActiveSheet
For Each rng In .UsedRange
rng.Value = rng.Value
Next rng
End With
End Sub
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Dim rng as Range
and
with ActiveSheet
are two unrelated, separate commands.
As such, they cannot be placed on the same line.

If that is how it is shown in some book you are looking at, that is a typo. It should be two separate lines.
 
Upvote 0
The macro is to change all formulas into values:
When I run it, I get the error message if I type as it is in book, that is, with "with ActiveSheet" on same line.
However, if I have it on separate line, it works. Why is that?

Compile Error
Syntax Error with the Dim line highlighted.

Macro with Error:
Sub ChangeToValue()
Dim rng as Range with ActiveSheet
For Each rng In .UsedRange
rng.Value = rng.Value
Next rng
End With
End Sub

Macro without Error:
Sub ChangeToValue()
Dim rng as Range
with ActiveSheet
For Each rng In .UsedRange
rng.Value = rng.Value
Next rng
End With
End Sub

You can't place the With statement on the same line as a Dim statement.
 
Upvote 0

Forum statistics

Threads
1,215,410
Messages
6,124,749
Members
449,186
Latest member
HBryant

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