Hans Strausl
Hans Strausl

Reputation: 614

Using variables in commands VBscript

I have the following code :

objIE.Document.All.a_l_1.click

But I want to do something like this :

objIE.Document.All. & some_var & .click

Upvotes: 0

Views: 1048

Answers (2)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

You can access the elements of the document.all collection by name, e.g.:

document.all("a_l_1").click

So there is no need for either Execute or Eval().

Update:

This .HTA:

<html>
 <!-- !! http://stackoverflow.com/questions/14595716/using-variables-in-commands-vbscript
 -->
 <head>
  <title>VariableDemo</title>
  <HTA:APPLICATION
    APPLICATIONNAME="VariableDemo"
  >
  <SCRIPT Language="VBScript">
   Sub AClick()
     Report document.all.bttA
     Dim sBtt
     For Each sBtt In Array("bttB", "bttC")
         document.all(sBtt).click
     Next
   End Sub
   Sub XClick(bttX)
     Report bttX
   End Sub
   Sub Report(bttX)
     document.all("txtA").innerText = bttX.innerText & ": " & Now() & vbCrLf & document.all("txtA").innerText
   End Sub
  </SCRIPT>
 </head>
  <body>
   <form>
    <button id="bttA" onclick="AClick">A</button>
    <button id="bttB" onclick="XClick Me">B</button>
    <button id="bttC" onclick="XClick Me">C</button>
    <br />
    <textarea id="txtA" rows="15" cols="40"></textarea>
   </form>
 </body>
</html>

'output'

demonstrates that

Report document.all.bttA                - access via named property

document.all("txtA").innerText = ...    - access via string literal

For Each sBtt In Array("bttB", "bttC")  - access via variable
    document.all(sBtt).click

all 'work', if the phase of the moon does not interfere.

Upvotes: 3

KevinH
KevinH

Reputation: 2054

Eval is what you want. It allows you to evaluate VBScript in string form, which then of course allows you to create that string however you wish. For example:

Dim myElement, evalResult
myElement = "a_l_1"
evalResult = Eval("objIE.Document.All." & myElement & ".click")

Upvotes: 1

Related Questions