There are several reasons your code fails.
If you want to work with objects, you assign them to variables using Set
. Even if you declare your variable as Variant
type, it will still work provided you use Set
. However, it is always advisable to explicitly declare the type of variable you want to work with. Why?
- It helps in stability, readability and allows you to detect type mismatches.
- It is faster.
So this would have worked:
Dim ClinObTemplate As Variant
Set ClinObTemplate = Sheets("clin obs").Range("A397,D429")
But of course, what Dan posted is advisable.
Now, as you can see there's a difference in how I've constructed the Range Object
syntax.
Let's take a look at your code:
Dim ClinObTemplate As Variant
ClinObTemplate = Sheets("clin obs").Range("A397, [D429]")
Above would've resulted to Error 1004
.
If you've noticed, I remove the []
brackets on the D429
address.
Why?
Because []
have special meaning in VBA
.
It is a shortcut for Evaluate
.
[D429]
is actually evaluating the address D429
and actually returns a Range Object
.
So to make your code work with brackets []
, it should be like this:
Dim ClinObTemplate As Variant
Set ClinObTemplate = Sheets("clin obs").Range("A397," & [D429].Address)
Now your ClinOnTemplate
variable contains the Range Object
A397 and D429.
If however you want to select the entire range in between those boundaries like A397:D429, write your code like this:
Dim ClinObTemplate As Variant
Set ClinObTemplate = Sheets("clin obs").Range("A397", [D429])
Or this:
Dim ClinObTemplate As Variant
Set ClinObTemplate = Sheets("clin obs").Range("A397:" & [D429].Address)
Or even this:
Dim ClinObTemplate As Variant
Set ClinObTemplate = Sheets("clin obs").Range([A397], [D429])
All codes assigns the Range Object A397:D429
to ClinObTemplate
variable.