tags:

views:

274

answers:

1

I am trying to implement an onclick event for an anchor tag on a website from Excel VBA. The following code gives me error message.

Set iePage = ieApp.document Set ieAnchor = iePage.getElementsByTagName("A").Item(5) ieAnchor.onclick = true

The error message is a run time error that says 'Not Implemented'

Can someone please advise on getting this event to fire?

BTW, I've used the basic iePage.Links(1).click event without a problem... but I need to execute a javascript function called from the anchor onclick event. Thanks,

A: 

If I understand your question correctly, you are trying to respond in VBA to the user clicking an anchor? If so you need to create an EventHandler for OnClick event. To do this you must restructure your code to meet the following criteria:

  1. You must declare said Anchor variable using the "WithEvents" keyword in order to respond to events.
  2. To use the "WithEvents" keyword you must declare your Anchor variable at the module level.
  3. You must also be inside a Class module to use the WithEvents keyword.
  4. Finally you need to create the Event Handler itself via the drop down menus in the top of the VBE or just paste in the code below.

    How to use the code: Create a Class Module named "MyClass" and paste in the following:
Option Explicit

Private WithEvents ieAnchor As MSHTML.HTMLAnchorElement

Public Sub Main()
    Dim iePage As MSHTML.HTMLDocument
    Set iePage = ieApp.document
    Set ieAnchor = iePage.getElementsByTagName("A").Item(5)
End Sub

Private Function mobjMyAnchor_onclick() As Boolean
    ''//Your Code Here
End Function

To use the code in the class you can then add a standard module and call the code like this:

Public Sub Example()
    Dim objMyClassVariable As MyClass
    Set objMyClassVariable = New MyClass
    objMyClassVariable.Main
End Sub

Edit: To call a JavaScript function you can just use the JavaScript URL scheme with the InternetExplorer.Navigate method. Ex: ie.Navigate "JavaScript:SomeFunc()". Or you can actually just cause the click to occur using the HTMLAnchorElement.Click method: ieAnchor.Click.

Oorang
Thanks.This will be very handy if I want to create my own onclick event, but I would like to use the onclick event to implement a javascript function stored in the HTML page. For instance, if I have a <select> list I can just enter document.getElementByName("list").onchange to call the onchange event within the document.Thanks.
Matt
Does the edit help you out?
Oorang
ieAnchor.Click defaults to the href code (if there is an href) and not the onclick event stored in the anchor tag. So the html block below would cause the page to navigate to yahoo.com and not call the yes() function. Thanks.<a onclick="yes()" href="http://www.yahoo.com">asdf</a>
Matt