Clear a Variant Variable

User avatar
Rudi
gamma jay
Posts: 25455
Joined: 17 Mar 2010, 17:33
Location: Cape Town

Clear a Variant Variable

Post by Rudi »

What is the best way to clear a variant variable at the end of the code?

- Erase varVariable
- Set varVariable = Nothing

TX
Regards,
Rudi

If your absence does not affect them, your presence didn't matter.

User avatar
HansV
Administrator
Posts: 78500
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Clear a Variant Variable

Post by HansV »

If the variable has been declared within the Sub or Function, there is no need to clear it at the end: VBA will automatically clear all local variables when the procedure or function ends. But if you'd like to clear it before the end of the code, you can use

varVariable = Null

(Erase works for arrays only, and setting the variable to Nothing works only if the variable is an object)
Best wishes,
Hans

User avatar
Rudi
gamma jay
Posts: 25455
Joined: 17 Mar 2010, 17:33
Location: Cape Town

Re: Clear a Variant Variable

Post by Rudi »

TX...
I should have mentioned that I am placing a very large range in the variable.

Code: Select all

Dim DataRange As Variant
Set rSource = Range("A1:Q50000")
DataRange = rSource
I need to clear it before the End Sub statement.

Would this variable be a Data Type Variable then instead of an Object?
So I should use:
DataRange = Null (Data Type)

In stead of:
Set DataRange = Nothing (Object)

TX
Regards,
Rudi

If your absence does not affect them, your presence didn't matter.

User avatar
HansV
Administrator
Posts: 78500
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Clear a Variant Variable

Post by HansV »

By assigning the values of a range to DataRange, DataRange becomes a two-dimensional array, not a Range object. So you cannot use Set. I'd use

DataRange = Null
Best wishes,
Hans

User avatar
Rudi
gamma jay
Posts: 25455
Joined: 17 Mar 2010, 17:33
Location: Cape Town

Re: Clear a Variant Variable

Post by Rudi »

TX for the confirmation.
:cheers:
Regards,
Rudi

If your absence does not affect them, your presence didn't matter.