CallByName with multiple levels of properties

85 views Asked by At

I want to use CallByName in VBA to read a specific data from such webpages. Those webpages have different html structures. In my case, there is a element that I need to refer 2 or 3 parent nodes and get an element with or tags. See the code:

element in all webpages I named MyElem

in one webpage I need this code:

MsgBox MyElem.parentElement.parentElement.parentElement.getelementsbytagname("tr")(3).innertext

in another webpage I need this code:

MsgBox MyElem.parentElement.parentElement.getelementsbytagname("div")(2).innertext

and so on ...

I want to write in VBA as below:

Select Case Webpage
     Case "webpage_1"
        property ="parentElement.parentElement.parentElement.getelementsbytagname("tr")(3).innertext"
     Case "webpage_2"
        property = "parentElement.parentElement.getelementsbytagname("div")(2).innertext"

      ' and so on ...

 End Select

MsgBox CallByName(MyElem, property, VbGet)

The problem is that CallByName don't support multiple levels of properties. I read similar topic here but it doesn't help to my case. Is there any idea?

2

There are 2 answers

4
Tim Williams On

Why not this?

Dim res

Select Case Webpage
     Case "webpage_1"
        res = MyElem.parentElement.parentElement.parentElement.getelementsbytagname("tr")(3).innertext
     Case "webpage_2"
        res = MyElem.parentElement.parentElement.getelementsbytagname("div")(2).innertext

      ' and so on ...

 End Select

MsgBox res
0
Harry S On
Function PropDotVal(wObjName$, PropNa$)

Dim wObj As Object: Set wObj = ObjFromStr(wObjName)

' ObjFromStr in module with lines like ' there has got to be an inbuilt vba function that does not need many case functions ' str obj 'Case "sTable": Set ObjFromStr = sTable ' ShapePlus 'Case "WHCages": Set ObjFromStr = WHCages ' spt

Dim Si%, NaA$() PropDotVal = "NA" On Error GoTo NotAvailable NaA = Split(PropNa, ".")

If UBound(NaA) > 0 Then

  ' PropNa format multi like  wObj.Objb.objc  etc  .prop
  '  convert wObj as  FredsFarm      with     PropNa as TopEnd.fill.backcolor.rgb
  ' to wobj as FredsFarm.TopEnd.fill.backcolor
  'and  Nsa(si) as "rgb" to CallByName from it

  For Si = 0 To UBound(NaA) - 1
     Set wObj = CallByName(wObj, NaA(Si), VbGet)
  Next Si

End If

PropDotVal = CallByName(wObj, NaA(Si), VbGet) NotAvailable:

End Function

enter code here