Pages

Thursday, March 15

Generate a random string in QTP/vbscript

Hello Friends,

Sometime script/application requires some input data as string which is unique. Random strings is helpful is this scenario. Lets see how to generate random input string in qtp.

Function GenerateRandomString(StrLen)
Dim myStr
Const MainStr= "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
For i = 1 to StrLen
  myStr=myStr & Mid(MainStr,RandomNumber(1, Len(MainStr)),1)
Next
GenerateRandomString = myStr
End Function

Here StrLen(argument) is the required length of the string. Call this function as below-

MsgBox GenerateRandomStrin(6)

It will generate a string of 6 characters.

In case of any queries, please post your comment.

12 comments:

  1. sir, plz explain this command and function of
    1>& Mid
    2> (1, Len(MainStr),1)
    myStr=myStr & Mid(MainStr,RandomNumber(1, Len(MainStr)),1)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. @Aryan

    1. & is used for concatenation of strings
    2. Mid(MainStr,RandomNumber(1, Len(MainStr)),1)

    in above line, mid function takes 3 arguments

    1. MainStr
    2. RandomNumber(1, Len(MainStr)) - result of this line will be passed as 2nd argument to Mid function

    3. 1

    ReplyDelete
  4. Wrong program as there is no Random function as Rnd there which does not take any argument

    ReplyDelete
  5. Use Below to generate a random number
    Dim max,min
    max=100
    min=1
    Randomize

    for i=1 to 100

    msgbox (Int((max-min+1)*rnd+min))

    next

    ReplyDelete
  6. Hi abhikansh,

    Sometimes, it is generating a random number like "="47"

    When I give input as 3 digits

    Please check this issue ...

    ReplyDelete
  7. Hello,
    I had a Question.
    Suppose consider in the datatable in 1 column we are having some "n" number of rows and from that n no. of rows I want to generate 10 random rows with that data in particular row.
    How to generate it??
    Its urgent can you get it for me.
    Regards,
    Shanmuk

    ReplyDelete
  8. It should generate by using Random function.

    ReplyDelete
  9. Thanks for your post 'Abhikansh Jain'!

    ReplyDelete
  10. Hi

    I have a query pls solve this at the earliest

    i have a data in notepad like

    one has spent rs 100 from his salary rs 10000
    two has spent rs 150 from his salary account rs 13000

    i want output to be printed like
    rs 10000
    rs 13000

    ReplyDelete
  11. str = "abcdefghijklmnopqrstuvwxyz"
    For i = 1 To 8 Step 1
    Randomize
    x = Int((26*Rnd)+1)
    char = Mid(str,x,1)

    str1 = str1&char
    Next

    MsgBox str1

    ReplyDelete
  12. Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this. Its really good. investire alle canarie con rendita garantita

    ReplyDelete