When using multiple With End With in the same Sub

JeffGrant

Well-known Member
Joined
Apr 7, 2021
Messages
516
Office Version
  1. 365
Platform
  1. Windows
Hi All,

I am in the process of cleaning up my code and cant seem to find an answer to this one.

Often I do.....

Sub ABC
With Sheet1
End With

With Sheet2
End With

With Sheet3
End With
End Sub

All I ever see is:

Dim ws as worksheet
Set ws = Sheeet1

With ws
End With

My questions are:
1, To make my code "cleaner" should I be changing the Set statement every time I change the With Statement?
2. With a Nested With statement, should I also be adding the Set statement?

My code works fine now, however, I do suspect that the structure of code is the cause of the occasional runtime errors that I get.

As always, thanks for your help.
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
I don't know if there is much difference, but you could always Loop if you're working with consecutive Sheets.
VBA Code:
Sub ABC()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    With ws
        'Some stuff
    End With
Next ws
End Sub
 
Upvote 0
I don't understand either question.
1) Your code (Often I do.....) doesn't use any Set statements.
2) Your code does not contain any nested With blocks. A nested With block would look like (please don't focus on the validity of the property references I used as I'm new to Excel vba and am writing from memory, as bad as that often is)
VBA Code:
With Sheet1
   .Range("A1") = "foobar"
      With .Range("A1")
          .Font.Color = vbRed
          .Interior.Color = vbYellow
     End With
End With
 
Upvote 0

Forum statistics

Threads
1,215,088
Messages
6,123,057
Members
449,091
Latest member
ikke

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