While writing this code
Worksheets.Add after:=Worksheets(Worksheets.Count)
VBA gives option of left parenthesis after the ADD method. But if I enclose
after:=Worksheets(Worksheets.Count)
in parenthesis is shows an error.
Why?
While writing this code
Worksheets.Add after:=Worksheets(Worksheets.Count)
VBA gives option of left parenthesis after the ADD method. But if I enclose
after:=Worksheets(Worksheets.Count)
in parenthesis is shows an error.
Why?
One use is to set a variable on-the-fly.
dim nuws as worksheet
set nuws = Worksheets.Add(after:=Worksheets(Worksheets.Count))
Because you are doing something with the returned value (e.g. setting it to a var), the parameters are required to be in parenthesis.
Another use is to rename the new worksheet in-line.
Worksheets.Add(after:=Worksheets(Worksheets.Count)).Name = "New WS"
Again, because you are doing something to the object newly created (e.g. naming it), the parameters are required to be in parenthesis.
Call Worksheets.Add as a sub. No error.
Worksheets.Add after:=Worksheets(Worksheets.Count)
Call Worksheets.Add as a function but not using the returned value. Produces error. Basically, you're telling it to return a value but giving it nowhere to store that value.
Worksheets.Add(after:=Worksheets(Worksheets.Count))
Call Worksheets.Add as a function and ignore the returned value. No error.
Call Worksheets.Add(after:=Worksheets(Worksheets.Count))
Call Worksheets.Add as a function and capture the returned value. No error.
SomeVar = Worksheets.Add(after:=Worksheets(Worksheets.Count))