Results 1 to 2 of 2

Thread: Selecting a random line

  1. #1

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


    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.
    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
    Randomize Timer
    Msgbox aLines(Int(Rnd * Ubound(aLines)))

    Aaron Young
    Analyst Programmer

  2. #2
    New Member
    Join Date
    Oct 1999


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



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