joehua
joehua

Reputation: 735

VBA: nested With with If statement

Is nested With allowed in VBA? If it is, how to use it with IF statement?

I have the following nested With combined with If statement and compiler gave me an error message saying "End With without With".

With
If
    With
    End With
Else
    End With   <- End With without With
End If

I put the first With outside the IF statement because the IF statement can use it. Since the above code didn't work, I tried a different way. Another error message was obtained if I moved the first With inside the IF statement. This time, the error message says "Else without If". That leads me to wonder if nested With is allowed in VBA.

A google search turned up one hit, which is not exactly the same as my problem.

Upvotes: 0

Views: 1137

Answers (2)

freeflow
freeflow

Reputation: 4355

The With End With structure applies to the current scope only. The scope of if else is different to else endif. Thus the with should either encompass the whole if statement or appear seperately in each scope.

It's perfectly possible to have a with end with nested inside other With End With structures. In this case you have to remember that the leading . Refers to the current scope.

Upvotes: 1

Harun24hr
Harun24hr

Reputation: 36870

Try like below

With
  If <Logical Test> Then
    With
      'Your action here
    End With
  Else
      'Your other actions here.
  End If
End With

Upvotes: 2

Related Questions