VBScript - Putting Array Element into GetElementById - vbscript

I am writing a VBScript that automatically interacts with some web pages. I am having trouble at the final step where the script needs to click on a link to make a booking. The link for each time will only be available if that time is free. The idea of my code is to simply select the first time available (I originally though I could do this by using Mid() and GetElementId as I know the first 7 chars of each link ID but couldn't get this working). The array contains the IDs for all possible times available in a day. Some will already have been taken so that ID will no longer exist on the form.
I have 2 problems:-
1) Neither getElementBy Id or the Document.All.Item().Click commands will accept an element from the array - I get an Object Required run time error.
2) If getElementId doesn't find a matching ID it simply throws an Object required error. I wasn't expecting this, I thought that my elem variable would be nothing or null and that I could test for this.
Can anyone give me any pointers?
'This is a shortened version of my array- there are lots more times!
Times(0)="bookBtn0810"
Times(1)="bookBtn0818"
Times(2)="bookBtn0826"
Dim TimeAvail
Dim i
Dim elem
TimeAvail = "No"
i = 0
Do While (TimeAvail = "No") or (i<3)
Set elem = IE.Document.GetElementById(Chr(34) & Times(i) & Chr(34)) 'Chr(34) is to add ""
if elem is nothing then
TimeAvail = "No"
i=i+1
else
TimeAvail = "Yes"
IE.Document.All.Item(Chr(34) & Times(i) & Chr(34)).click
end if
Loop

Now, unless I'm being very silly, you won't be able to sit a variable to a non-existent element.
The only thing I can think of is to add:
On Error Resume Next
At the beginning, so it skips the error message. You may need to handle the error separately yourself.

Related

How can I get the position of a CAD part via VBscript?

I want to write a VBScript, which outputs the position of a CAD part (x,y,z). The Input should be the partnumber. This is what I tried.
Sub CATMain()
dim pos(11)
for n = 1 to CATIA.Documents.Count
set Dokument = CATIA.Documents.Item(n)
for i = 1 to Dokument.product.products.Count
set InstDokument = Dokument.product.products.item(i)
If InstDokument = "my_part" Then
msgbox InstDokument.Name
InstDokument.Position.GetComponents pos
msgbox "Origin Point: X= " &pos(9) &" Y= " &pos(10) &" Z= " &pos(11)
End If
next
next
End Sub
I got an error in line 8 column 2. The object does not have the property or method.: Dokument.product
How can I solve that?
There are several problems with your code.
At the root is probably this:
set Dokument = CATIA.Documents.Item(n)
The CATIA documents collection will contain many documents which do not have windows and which the CATIA application maintains for it's own various internal purposes. So it is not assured that CATIA.Documents.Item(n) actually contains a CATProduct.
In most cases one is interested in the current active document, and it is retrieved like this:
Set Dokument = CATIA.ActiveDocument
Otherwise you can test for it
Set Dokument = CATIA.Documents.Item(n)
if typename(Dokument) = "ProductDocument" Then ...
Even after that you have problems. You are comparing the Document object to a string... and other things. Also without recursion you may never find your target instance if it is deeper then at the first level. It may also be possible that search may be a better way to find your instance then "Reading the tree".
Once you have corrected all your infrastructure errors your method for getting the transformation matrix is basically correct.

vbscript Execute: exit external For

Execute in vbscript is used to parse strings into inline instructions. However, I can't use it to break For loops. The following won't work:
For i = 1 To 10
msgbox i
Execute("Exit For")
Next
Does somebody know any workaround for it to work? Or any way for Exit Sub/Exit Function work? I tried ExecuteGlobal, but it also raises "invalid exit instruction" error.
I used it as a form of "import" throughout my code and it is going to be time consuming to implement another form of import all over again, so I am searching for a way to make it work before considering to change the project.
EDIT: more examples
In short, I tried to do a partial override of a semi-abstract method, but can't use Exit For against a For outside the Execute block.
Dim names_array 'this array will be populated in another Sub
'this method will loop though all elements of an array and insert some items into a database...
'but the method does not know (how to)/(if it will really) insert into the database!
'all it knows is: it has to loop though the array... and, if needed, finish earlier
'the insertion part will have to be described before running, like a 'partial override' of an abstract method
'that is because I know how part of the method must be, but the details will be diferent for each database
'I don't want to override every method entirely!
Sub insert_into_database
For i = 0 To UBound(names_array)
name = names_array(i)
Execute(core_op) 'here comes the core operation, it is what I override!
Next
End Sub
'for some databases, core_op will be simple:
core_op = "objRecordSet.Open ""INSERT INTO videos (title, date_time) VALUES ('"" & name & ""', Now)"", objConnection"
'for others, it may be complex:
core_op = "If name=""18+ only"" Then"
core_op = core_op + " MsgBox ""You tried to insert nasty things. System will now halt."""
core_op = core_op + " Exit For"
core_op = core_op + "Else"
core_op = core_op + " objRecordSet.Open ""INSERT INTO videos (title, date_time) VALUES ('"" & name & ""', Now)"", objConnection"
core_op = core_op + "End If"
'the string won't be loaded this way, it will come from an external file
'there are other methods that operate like this, but not all of them need Exit For
That is closer to my project. The reality is: the code for the overrides will come from an external file and will be stored in a dictionary.
Sorry if it seems a mess, that is the way I tried to make vbscript more java-like regarding reusability.
Exit statements are parts of compound statements (loops, routines) and must be 'compiled' in their contexts. So there is no workaround and you have to redesign your import strategy. Perhaps you should publish your current approach.
Update wrt comment (partial override of the method):
Use GetRef and pass "function pointers", or invest in some classes and send objects to the enclosing function.

How to clear the contents of an array in vbscript?

I have declared a two dimensional array in the function library and associated it with a test. In action1 of the test, I tried to clear the array using "erase" statement.
My code -
In Function Library,
Dim strVerifyAry(25,6)
In action1,
erase strVerifyAry
Error message
Run Error - Type mismatch: 'Erase'
How to clear the contents of this array?
Works for me in plain VBScript, so it's most likely an issue with whatever engine QTP uses for running VBScript code. You should be able to emulate the behavior of Erase for a 2-dimensional array like this:
Sub EraseArray(ByRef arr)
For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
If IsObject(arr(i, j)) Then
Set arr(i, j) = Nothing
Else
arr(i, j) = Empty
End If
Next
Next
End Sub
Or like this, if you don't want to set fields containing objects to Nothing:
Sub EraseArray(ByRef arr)
For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
arr(i, j) = Empty
Next
Next
End Sub
I do not exactly understand why, but you can create a sub like
Public Sub DoErase (byRef Ary)
Erase Ary
End Sub
in the library, and call it from within the action like this:
DoErase StrVerifyAry
and that works.
Update: No it doesn't. The array is successfully passed to DoErase, and the DoErase call works fine, but the test afterwards still can reference the array elements that Erase was supposed to be erasing.
If the test declares the array, it works fine (Erase erases the elements).
This is very strange and probably has to do with the quirky scopes in function libraries.
Please let us know if you ever find out what's going on here...
This drove me nuts for an entire afternoon so I wanted to post an answer for future reference. I filled an array using the Split command and then needed to Erase it before the script looped back through the process again. Nothing I tried would erase or clear the array and the next use of Split just appended to the previous array elements.
By trying the 'array=Nothing' loop above, I finally managed to generate a "This array is fixed or locked" error which I researched. Turns out I had used the array in a 'For Each..Next' loop which locks the array so it can't be erased or cleared. More info is available HERE:
You can use a Dictionary collection rather than an array in some circumstances. Then use RemoveAll when you want to clear it. That doesn't help when your array was created by a split function, or whatever, but it can help in other use cases.
Set myDict = CreateObject("Scripting.Dictionary")
...
myDict.RemoveAll
Refer to: https://www.w3schools.com/asp/asp_ref_dictionary.asp

LotusScript - Setting element in for loop

I have an array set up
Dim managerList(1 To 50, 1 To 100) As String
what I am trying to do, is set the first, second, and third elements in the row
managerList(index,1) = tempManagerName
managerList(index,2) = tempIdeaNumber
managerList(index,3) = 1
But get an error when I try to do that saying that the object variable is not set. I maintain index as an integer, and the value corresponds to a single manager, but I can't seem to manually set the third element. The first and second elements set correctly.
On the flip side, I have the following code that will allow for the element to be set,
For x=1 To 50
If StrConv(tempManagerName,3) = managerList(x,1) Then
found = x
For y=3 to 100
If managerList(x,y) = "" Then
managerList(x,y) = tempIdeaNumber
Exit for
End If
Next
Exit For
End If
Next
It spins through the array (laterally) trying to find an empty element. Ideally I would like to set the index of the element the y variable is on into the 3rd element in the row, to keep a count of how many ideas are on the row.
What is the best way to keep a count like this? Any idea why I am getting a Object variable not set error when I try to manually set the element?
object variable not set means that you are trying to call methods or access properties on an un-initialized object. I don't see anything like that in the code snippets you have published, are you sure the error occurs in those lines?
A good way to pin-point errors is to include the module and line number in the error message. Add this around your subroutine to get a more detailed message:
Sub Initialize
On Error Goto errorthrower
//
// your code goes here...
//
Exit sub
ErrorThrower:
Error Err, Str$(Err) & " " & Error & Chr(13) + "Module: " & Cstr( Getthreadinfo(1) ) & ", Line: " & Cstr( Erl )
End sub
(I originally found this on Ferdy Christants blog)
It's not quite clear what problem you are trying to resolve here, but it looks like you have 1..50 "managers" that can have 1..100 "ideas" ? I'd make a class for managers instead:
Class manager
Private managername As String
Private ideas(1 To 100) As String
Sub new(managername As String)
Me.managername=managername
End Sub
// whatever methods you need....
End Class
Then, I'd keep track of them with a list of these objects:
Dim managerlist List As manager
Dim key As String
key = Strconv(tempmanagername,3)
if not iselement(managerlist(key)) then
set managerlist(key) = new manager(key)
end if
Dim currentmanager As manager
Set currentmanager = managerlist(key)
This is only an example to get you started, you will have to adapt this to solve your actual problem.

VBScript: Finding the number of non-null elements in an array

What is the "best" way to determine the number of elements in an array in VBScript?
UBound() tells you how many slots have been allocated for the array, but not how many are filled--depending on the situation, those may or may not be the same numbers.
First off there is no predefined identifier called vbUndefined as the currently accepted answer appears to imply. That code only works when there is not an Option Explicit at the top of the script. If you are not yet using Option Explicit then start doing so, it will save you all manner of grief.
The value you could use in place of vbUndefined is Empty, e.g.,:-
If arr(x) = Empty Then ...
Empty is a predefined identify and is the default value of a variable or array element that has not yet had a value assigned to it.
However there is Gotcha to watch out for. The following statements all display true:-
MsgBox 0 = Empty
MsgBox "" = Empty
MsgBox CDate("30 Dec 1899") = True
Hence if you expect any of these values to be a valid defined value of an array element then comparing to Empty doesn't cut it.
If you really want to be sure that the element is truely "undefined" that is "empty" use the IsEmpty function:-
If IsEmpty(arr(x)) Then
IsEmpty will only return true if the parameter it actually properly Empty.
There is also another issue, Null is a possible value that can be held in an array or variable. However:-
MsgBox Null = Empty
Is a runtime error, "invalid use of null" and :-
MsgBox IsEmpty(Null)
is false. So you need to decide if Null means undefined or is a valid value. If Null also means undefined you need your If statement to look like:-
If IsEmpty(arr(x)) Or IsNull(arr(x)) Then ....
You might be able to waive this if you know a Null will never be assigned into the array.
I'm not aware of a non-iterative method to do this, so here's the iterative method:
Function countEmptySlots(arr)
Dim x, c
c = 0
For x = 0 To ubound(arr)
If arr(x) = vbUndefined Then c = c + 1
Next
countEmptySlots = c
End Function
As Spencer Ruport says, it's probably better to keep track yourself to begin with.
There's nothing built in to tell you what elements are filled. The best way is to keep track of this yourself using a count variable as you add/remove elements from the array.

Resources