Results 1 to 2 of 2

Thread: Selecting a random line

  1. #1

    Thread Starter
    Guru Aaron Young's Avatar
    Join Date
    Jun 1999
    Location
    Red Wing, MN, USA
    Posts
    2,176

    Post

    If the file was a Random Access File, (All Lines/Records are the Same Length) then you could use the Open.. For Random Access Read Statement and the Get Method to randomly pick a line from the File.

    Otherwise, you will need to read the whole file in, parse it into it's individual lines, then seelct one at random, eg.
    Code:
    Dim iFile As Integer
    Dim iPos As Long
    Dim sFile As String
    dim iLines As Integer
    Dim aLines() As String
    
    iFile = FreeFile
    Open "C:\MyFile.txt" For Input As iFile
        sFile = Input(LOF(iFile), iFile)
    Close iFile
    While Len(sFile)
        iPos = Instr(sFile, vbCrLf)
        If iPos = 0 Then iPos = Len(sFile) + 1
        ReDim Preserve aLines(iLines)
        aLines(iLines) = Left(sFile, iPos - 1)
        sFile = Mid$(sFile, iPos + 2)
        iLines = iLines + 1
    Wend
    Randomize Timer
    Msgbox aLines(Int(Rnd * Ubound(aLines)))

    ------------------
    Aaron Young
    Analyst Programmer
    aarony@redwingsoftware.com
    adyoung@win.bright.net

  2. #2
    New Member
    Join Date
    Oct 1999
    Posts
    12

    Post

    Hi. Can someone show me how to select a random line from a file, and assign it to a variable?

    Thanks

    ------------------

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width