How to display variable name not its value in vb - vbscript

I am trying to get the variable name used in for each loop printed in vbs but unable to do so.
x=2, y=3, z=7
a = array (x,y,z)
for each element in a
wscript.echo element
next
The above example prints the variable element value (2/3/7) rather than element name (x/y/z). how do you i get to print the element name.
Please Help!

Did you consider using a dictionary?
Dim dict : Set dict = CreateObject("Scripting.Dictionary")
dict.item("x") = 2
dict.item("y") = 3
dict.item("z") = 7
dim key, value
For Each key in dict.Keys
value = dict.item(key)
wscript.echo key & " = " & value
Next

You can't in normal programming. You are the programmer, you know the names. You put the names in the output (msgbox "Variable name is A " & A).
You can put your code into strings, process it how you want, then execute it with eval or execute (see Help).
You can do the above but use the script control (see Google).
But you know the names, and if you want to display them simply, then you type their names into the message strings.

x=2, y=3, z=7
a = array (x,y,z)
names = array ("x","y","z")
for each element in names
wscript.echo element
next
If you want to show each element with his value:
x=2, y=3, z=7
a = array (x,y,z)
names = array ("x","y","z")
for i=0 to 2
wscript.echo names(i) & "=" & a(i)
next

Related

VBScript create list, split list items and trim them

I'm trying to create code that would add variables to list. Then it would split all of list elements by :, returning only the second part. In the end all returned strings would be trimmed.
To give you better understanding let me show you an example:
Add "a : b " and " c : d " to the list.
Split elements so only "b " and "d " are returned.
Trim "b " and "d ".
So far I have came up with something like this but it doesn't work and I have no idea why.
Set list = CreateObject("System.Collections.ArrayList")
list.Add "bob : kid"
list.Add "ryan : alex"
list.Add "kate : andy"
list.Add "alice : mandy"
For Each item In list
Dim item As String
Dim words As String() = item.Split(New Char() {":"c})
For Each word In words
WScript.Echo word
Next
Next
Your code doesn't work because it's not valid VBScript. You have several issues:
VBScript doesn't support typed variable declarations (Dim var As Type). Use Dim var if you want to explicitly define a variable. Note, however, that in VBScript defining variables is only required when you put Option Explicit at the beginning of your script.
VBScript doesn't support combined declaration and definition of variables (Dim var = value). You need two separate statements for defining a variable and assigning a value to it. The two statements can be put in one line by separating them with a colon (Dim var : var = value), but they're still two separate statements.
In VBScript string is a primitive data type. VBScript strings are not objects with properties. For splitting a string use the Split() function.
Don't re-define your loop variable inside your loop.
Change your loop to something like this and it should do what you want:
For Each item In list
Dim words : words = Split(item, ":")
For Each word In words
WScript.Echo Trim(word)
Next
Next
If you want just the second element from each split item you'd do something like this:
Dim words : words = Split(item, ":")
WScript.Echo Trim(words(1))
or like this:
WScript.Echo Trim(Split(item, ":")(1))

Why does this classic ASP loop to split a textarea into lines not work?

I am trying to put a textarea into an array, splitting it where there are new lines. I know that docnos does in fact contain the characters found within the textarea. Can anyone please tell me why this doesn't work? It is not putting anything into the array for some reason.
docnos = dbencodeStr(Request.form("docnos"))
Dim myArray
myArray = Split(docnos, vbCrLf)
for i = 0 to UBound(myArray,2)
tempstr = trim(myArray(0,i))
strSQL = "insert into DocumentNumbers (queryid, documentnumber) values('"&queryid&"','"&tempstr&"');"
Response.write(strSQL)
Response.write(tempstr)
Set rs = TransactionQueriesConn.Execute(strSQL, ,adCMdTExt)
next
Given myArray = Split(docnos, vbCrLf), UBound(myArray,2) will throw an "Subscript out of range" error (no second dimension). Remove the "On Error Resume Next".
Assuming myArray holds an one dimensional array of lines, the loop needs UBound(myArray) or UBound(myArray,1).
If docnos contains "234234234<BR>567567<BR>345345345", you need to Split on <BR>. Evidence:
>> s = "234234234<BR>567567<BR>345345345"
>> WScript.Echo Split(s, "<BR>")(1)
>>
567567

How to remove duplicate from an array using vb script without using dictionary objects?

I am trying to remove duplicates from array using for loop and conditional statement.But I am unable to create new array without any duplicates.There is xls having country name with duplicates,i am aiming to remove duplicates and create a new array with unique country names.
For e.g
strFilePath="D:\Country.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible=True
Set objWorkbook = objExcel.Workbooks.Open (strFilePath)
Set objSheet=objExcel.Sheets("Country")
objExcel.DisplayAlerts = False
objExcel.AskToUpdateLinks = False
objExcel.AlertBeforeOverwriting = False
Dim A(100)
Dim B(100)
For i = 2 To 6 Step 1
k = i-2
A(k)=objSheet.Cells(i,1).Value
Next
B(0)=A(0)
For j = 0 To 4 Step 1
strIt=A(j)
For m = 1 To 4 Step 1
reslt = StrComp(A(m),strIt,1)
If(reslt = 1 Or reslt = -1) Then
c=1
B(c)=A(m)
c=c+1
End if
m=m+1
Next
Next
Two options, depending on your needs:
Try using a hash table of the country names. When entering values in to the hash table you could do a simultaneous check to see whether you encounter an identical value. If it finds one it will abort entering the new value and continue with the next one, otherwise it will be entered in to the table. At the end of it you will have your list of unique country names.
Sort the list of countries and then do a second pass that removes duplicate countries (since duplicates will now be grouped together)
Problems with both of these methods is that they dont preserve original order unless you keep some sort of "original index" value and then sort based on that value once you remove duplicates.
Here's how I usually do it:
Dim uniqueentries()
ReDim uniqueentries(-1)
' Here you could go through your existing array and
' call "GetUniqueEntries" sub on each entry, e.g.
For Each i In oldarray
GetUniqueEntries i
Next
Sub GetUniqueEntries(newentry)
Dim entry
If UBound(uniqueentries) >= 0 Then ' Only check if uniqieentries contains any entries
For Each entry In uniqueentries
If newentry = entry Then Exit Sub ' If the entry you're testing already exists in array then exit sub
Next
End If
ReDim Preserve uniqueentries(UBound(uniqueentries) + 1) ' Increase new array size
uniqueentries(UBound(uniqueentries)) = newentry ' Add unique entry to new array
End Sub
This could be done more simpler way by using Split command. Please check the below solution, if any clarification let me know.
Dim aDupl
Dim aNew, strNew
aDupl = Array("A", "B", "A", "D", "C", "D")
strNew = ""
For iCnt= 0 To UBound(aDupl)
If InStr(strNew,aDupl(iCnt) ) = 0 Then
strNew =strNew&aDupl(iCnt)&","
End If
Next
aNew = Split(strNew, ",")
For iCnt=0 To UBound(aNew)
WScript.Echo aNew(iCnt)
Next

VBScript to combine rs values, loop and add to duplicate(s)

I've written a lot of IF statements in VBScript, but haven't gone much beyond that so apologize for my lack of experience. I hope what I'm asking is simple to do.
I want to output item identifiers created by three combined recordset field values and add "B" "C" "D" etc., to any duplicates. Duplicates are rare, but do happen occasionally. I want to do this for meaningful item identification which autonumbers do not provide.
The following example works to combine fields, but then I need to include script to loop and find the duplicates and add the appropriate alpha character.
FYI: a = alpha character, b = alpha character, c = reformatted date
<% Dim idCode
a = (rs_table.Fields.Item("CodeA").Value)
b = (rs_table.Fields.Item("CodeB").Value)
c = (fixedDate(rs_table.Fields.Item("Date").Value))
idCode = (a) & (b) & (c)
Response.write idCode
%>
example output: LC032414
example dupe output: LC032414B
Thanks, I'm almost afraid to ask and may find this more pain than what it's worth!
I would probably use a Dictionary to store the ID's, since you can add each as a key (which must be unique) and test the Dictionary for its existence. Something like this:
' Early on... create a dictionary...
Set d = CreateObject("Scripting.Dictionary")
' Loop through your records...
Do Until rs_table.EOF
' Determine your ID...
idCode = rs_table("CodeA") & rs_table("CodeB") & fixedDate(rs_table("Date"))
' Check for existence in the dictionary...
If d.Exists(idCode) Then
' ID already exists. Keep testing suffixes until we find an availability...
strLetter = "B"
Do While d.Exists(idCode & strLetter)
strLetter = Chr(Asc(strLetter) + 1)
Loop
d.Add idCode & strLetter, "" ' Add the ID/key. The value is unimportant.
Else
' This ID doesn't exist yet. Just add it.
d.Add idCode, "" ' Add the ID/key. The value is unimportant.
End If
rs_table.MoveNext
Loop
When it comes time to print your ID's, you can just iterate the dictionary's Keys collection:
For Each k In d.Keys
Response.Write k
Next

QTP: Object Required errors when Object is valid

I have the following VBScript in a reusable action:
'Gather links
Browser("1").Navigate "http://InternalWebmail/something/inbox.nsf"
set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
set links = Browser("1").Page("Webmail").ChildObjects(oDesc)
Dim links2
links2 = ""
'Filter out irrelevant links
For i = 0 To links.Count-1
If lcase(trim(links(i).GetROProperty("text"))) = lcase(trim(DataTable("ExpectedFrom", dtGlobalSheet))) Then
links2 = links2 + "," + links(i).GetROProperty("url")
End If
Next
Dim final
final = split(mid(links2,2),",") 'Remove leading comma and split into array
'For each link (i.e. for each E-mail received):
'Effectively giving a reusable action an input parameter, I hope
For i = 0 To final.Count - 1 'error: Object Required
DataTable("url","CheckHeader") = final(i)
RunAction "CheckHeader", oneIteration
Next
Everything runs just fine, until I get to the declaration of the loop at the bottom of the snippet. There, QTP gives me an error "Object Required" and refuses to elaborate.
i has a leading value of 58, though I've tried setting it to 0 prior to entering the loop.
final is an array of 6 strings, each a URL. All have a value.
If I msgbox(final(2)), I see the value of final(2) as being valid.
isobject(final(1)) = false
final(1) has the correct value
msgbox(final is nothing) and msgbox(final(1) is nothing) yield the same error.
It looks as if the array is null but somehow the array has members?
How is this possible?
What is QTP talking about?
In vbscript arrays don't have a Count property, you should use UBound
x = split("how now brown cow")
' MsgBox x.Count ' error
MsgBox UBound(x) ' 3
The reason .Count worked for the first loop is that ChildObjects does not return an array, it returns a COM collection object. That is also why you had to use the Set statement when assigning to links but not when assigning to final.

Resources