use "SET" statement with "iif "

smallxyz

Active Member
Joined
Jul 27, 2015
Messages
392
Office Version
  1. 2021
Platform
  1. Windows
Hi All,

Is it illegitimate for VBA to use "SET" statement with "iif" ?

I got an error for the below coding︰

VBA Code:
    Dim Rng As Range, URng As Range    
    Set URng = Nothing
    Set Rng = Range("A1")
    Set URng = IIf(URng Is Nothing, Rng, Union(URng, Rng))
    
    MsgBox URng.Address(1, 1)


Is that the only correct writing is as follows?
VBA Code:
    Dim Rng As Range, URng As Range    
    Set URng = Nothing
    Set Rng = Range("A1")

    If (URng Is Nothing) Then
        Set URng = Rng
    Else
        Set URng = Union(URng, Rng)
    End If
    MsgBox URng.Address(1, 1)

My reason of combining "SET" with "IIF" mainly is to simplify the code length for better readability. If that is disallowed in VBA, I will stick to the "If Then Else" statement.

Thanks all.
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
In that instance you cannot use IIf
IIf always evaluates both the 'True' part and the 'False' part.
In your example, the False part is Union(URng, Rng) and since URng is Nothing that evaluates to an error
 
Upvote 0

Forum statistics

Threads
1,214,851
Messages
6,121,931
Members
449,056
Latest member
denissimo

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