Search code examples
excelvbainternet-exploreremail

Press "New mail" button in Microsoft 365 email using VBA


I am trying to send an email over Microsoft 365 using IE as the browser. I am currently having difficulty getting VBA to create a new email and am trying to do so by simply telling it to click the "New Mail" button which has the following HTML code:

<button autoid="_n_j" type="button" class="_n_j2 o365button" aria-labelledby="_ariaId_31" regionbehavior="1">
<span class="_n_l2 owaimg ms-Icon--plus ms-bcl-tp ms-bg-transparent ms-icon-font-circle ms-fcl-tp ms-icon-font-size-20-circle" role="presentation"></span>
<span class="_n_k2 ms-font-weight-regular ms-font-color-themePrimary" id="_ariaId_31">New mail</span>
</button>

I am trying to press this using the following VBA code:

Dim objButton As Object
    Set objButton = IE.Document.getElementById("_n_j2 o365button")
    objButton.onfocus
    objButton.onclick

But am getting a run time error. I think this is because the button is using javascript (page doesnt reload when pressed, just updates). Any ideas how to do this?


Solution

  • Try IE.Document.GetElementsByClassName("_n_j2 o365button")(0).Click

    You can't use .GetElementByID() because the button hasn't been assigned an ID.

    I've used .GetElementsByClassName() because we know that the button has a class assigned, however a class is not unique. This method returns a collection of all elements with this class - without seeing the whole HTML, I'm going to make an assumption that all buttons on the page share this class.

    The (0) tells the code to click the first item stored in the collection.

    (Again, I'm going to assume you don't have something like Option Base 1 declared)

    You might have to iterate through the collection and somehow test each item to see which button you need and change the (0) accordingly.