Set Keyword

xcel

New member
Joined
May 13, 2018
Messages
8
Reaction score
0
Points
0
Excel Version(s)
2016
Hello,
I am a newbie on vba. I am confused when should i use a set keyword when defining a object variable. Up to now i was in a believing that we need to use a set keyword every time we declare a object variable. In the example below we have not used a set key word after declaring the variable but the code still runs fine. I did not get it when to use a set keyword and when not too. Can anyone please clarify me the when to use a set keyword

many thanks

Sub Test_data (ByVal Myrange As Range)

Dim Cell As Range
For Each Cell In Myrange
If Cell.Column = Range("A:A").Column Then
If Cell.Value <> "" Then
Cells(Cell.Row, "B").Value = Now
Else
Cells(Cell.Row, "B").Value = ""
End If
End If
Next Cell
End Sub
 
If you set Option Explicit at the start of your code, then you need to define all variables. This is a good habit to have as it ensures that you do not mis-code any variable. It will also kick out compile errors and help to keep your code clean and help others to follow and understand your code.
 
@xcel
Hi,
When posting code, please wrap it with code tags ( Edit code - select code - click the #button.)
It keeps the macro's structure and makes it easy to copy and handle.
Thank you
 
You do need to use Set when you assign an object to a variable explicitly. In the case of a For Each loop, the assignment is done implicitly by VBA so you do not have to do it.
 
Back
Top