I found an unexpected (at least for me) behavior using a variable declared as Object
in Excel-vba.
I was trying to extract some data from an html page and so I was using a routine like this:
sub Test
Dim htmlPage As htmlDocument
'This is the interesting variable
Dim DataTable As Object
Dim DataCollection As Object
'Code to get the html page
Set DataTable = htmlPage.getElementById("a name")
Set DataCollection = DataTable.getElementsByClassName("another name")
' Code to use DataCollection
end Sub
If I try to run this code on the line Set DataCollection = DataTable.getElementsByClassName("another name")
I get the error
Run-time error '438'
Object doesn't support this property or method
After the first Set
command the DataTable
variable has become of type Object/HTMLDivElement
so in principle it should have the method getElementsByClassName
.
What I do not understand is that if I declare the variable from the beginning as HTMLDivElement
(without changing anything else in the cose) such as:
Dim DataTable As HTMLDivElement
the above code runs correctly without errors. In that case the DataTable
variable is of type HTMLDivElement/HTMLDivElement
.
What is the difference in declaring a variable as generic Object
vs specifying its type from the beginning? And why the first version of the code does not work?