Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object supports method in vba?

Is it possible to check whether an object supports a certain method without an error handler in VBA?

I've found numerous duplicates asking the question for for example JavaScript and Symphony2, but not yet in VBA.

I would like to use a .sendkeys "{ENTER}" command to an ie.document class item and learning how to check whether the object supports a method allows me to write cleaner code in the long run.

example code:

Set elements(17) = ie.document.getElementsByClassName("ng-binding ng-scope")
for each item in elements(17)
    item.sendkeys "{ENTER}"
next item
like image 958
a.t. Avatar asked Sep 26 '17 19:09

a.t.


1 Answers

Short of looking at the documentation for the API you're using, you can't.

At least not on late-bound code. By definition, late-bound code is resolved at run-time, which means you have no compile-time way of validating whether a member will be available on that object's interface - that's why this code compiles:

Option Explicit

Public Sub Test(ByVal o As Object)
    Debug.Print o.FooBarBazz
End Sub

Or this somewhat more realistic one:

Debug.Print ThisWorkbook.Worksheets("Test").Naame 'Worksheets.Item returns an Object

The only way to know before run-time whether a member is supported, is to use early-bound calls:

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Test")
Debug.Print ws.Naame ' typo won't compile!

Of course it's not that simple, because even early-bound interfaces can have a COM flag saying they're "extensible". Excel.Application is one such interface:

Debug.Print Excel.Application.FooBarBazz ' compiles!

But I'm drifting.

You say "without error handling" ...does this count?

On Error Resume Next
item.sendkeys "{ENTER}"
'If Err.Number = 438 Then Debug.Print "Not supported!"
On Error GoTo 0
like image 82
Mathieu Guindon Avatar answered Sep 21 '22 12:09

Mathieu Guindon