VBA error when referencing a defined worksheet

kgkev

Well-known Member
Joined
Jun 24, 2008
Messages
1,291
Office Version
  1. 365
Platform
  1. Windows
Hi,

I have isolated a piece of code which has been working 3 years which stopped working.
I have found a work around but I would like to know why the original code wouldn't work

This code no longer works
It gives
Runtime Error '9'
Subscript out of range
VBA Code:
Sub test()
Dim MS As Worksheet
Set MS = Sheets("Chasing")
With MS
    .Range("H5", .Range("K5000")).ClearContents
End With
End Sub

This code works and has the desired effect.
VBA Code:
Sub test()
With Sheets("Chasing")
    .Range("H5", .Range("K5000")).ClearContents
End With
End Sub


even this works
VBA Code:
Sub test()
Dim MS As Worksheet
Set MS = Sheets("Chasing")
With MS
    Sheets("Chasing").Range("H5", .Range("K5000")).ClearContents
End With
End Sub


I use "MS....." throughout the module, probably 30+ instances and all other lines of code still function correctly.

Thanks for helping
 
As part of the fault finding it was just clearing the contents of the used cells. This was modified to a big range and I didn't change it back.

now changed to your suggestions
 
Upvote 0

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.

Forum statistics

Threads
1,223,227
Messages
6,170,849
Members
452,361
Latest member
d3ad3y3

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