toop
toop

Reputation: 11294

VBScript - Generate a file with x lines of random text

What code do I need to generate a file with a specified number of lines.

ie. have some variable called num_lines = 8743 then for each line generate a random string that is between 200 and 300 characters long.

Save this to a file.

start of code to randomise:

For x=200 To 300
    Randomize
    vChar = Int(89*Rnd) + 33
    Rndz = Rndz & Chr(vChar)
  Next

Upvotes: 0

Views: 12174

Answers (2)

SameOldNick
SameOldNick

Reputation: 2437

Here's a fix of the RandomString function from the answer:

Function RandomString( ByVal strLen )
    Dim str, min, max

    Const LETTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
    min = 1
    max = Len(LETTERS)

    Randomize
    For i = 1 to strLen
        str = str & Mid( LETTERS, Int((max-min+1)*Rnd+min), 1 )
    Next
    RandomString = str
End Function

The other function is broken and was incorrectly getting a random character from the salt string. This function will return a random string containing letters and/or numbers.

Upvotes: 2

JMax
JMax

Reputation: 26591

You can use a first function to create a random string:

Function RandomString( ByVal strLen )
    Dim str
    Const LETTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
    Randomize
    For i = 1 to strLen
        str = str & Mid( LETTERS, Int(strLen*Rnd+1) )
    Next
    RandomString = str
End Function

Source

And then write it to a file thanks to Scripting.FileSystemObject:

Const ForAppending = 8
Const max = 300
Const min = 200
Dim i As integer, lLines As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\service_status.txt", ForAppending, True)
Randomize
For i = 1 To num_lines
   lLines = Int((max-min+1)*Rnd+min) 
   objTextFile.WriteLine(RandomString(lLines))
Next
objTextFile.Close

Source

Upvotes: 3

Related Questions