简体   繁体   中英

Excel VBA copy the value of a label from Internet Explorer

I'm trying to retrieve the value "CONGE STATUTAIRE" from the following html code

<span class="DescriptionLabel" id="lblProjectDescription">CONGE STATUTAIRE</span>

I've tried this

nom_proj = IE.Document.getElementsByClassName("DescriptionLabel")(0).innerText  

The code pass this line without problem but the the value of nom_proj is " ", and I would have hope to get "CONGE STATUTAIRE" for result.

Could anyone tells me what's wrong with it? The rest of my code is working ie I can retrieve value by using the getelementbyID method.

Any help will be welcomed.

I would use the getElementById() method, to make sure it can return only one HTML element and not a collection of objects:

nom_proj = IE.Document.getElementById("lblProjectDescription").innerText

However, the reason why you get "" is most probably that the collection returned by getElementsByClassName() has more than one element (often, when retrieving object by class names). Which means: in the Document of your browser there will be most probably more elements that are styled with the CSS class DescriptionLabel ; for example, something like this:

<div name="emptyRow" class = "DescriptionLabel"></div>

You can test if there are more than one element by:

1) either, adding a watcher to IE.Document.getElementsByClassName("DescriptionLabel") ;

2) or, printing all the elements inside, I bet my hat you'll find inside more than one:

For Each obj In IE.Document.getElementsByClassName("DescriptionLabel")
    Debug.Print obj.InnerText
Next obj

GENERAL SUGGESTION : if an HTML object has an id , use the getElementByID ; that method returns a single object, not a collection, so even if you would be sure that the collection will contain a unique element, it would anyway be less clean and efficient in terms of coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM