简体   繁体   中英

writing output to the text file

I need to find the first 20,000 random numbers generated by RND -1. I have written the following code, which allows me to see those numbers in the Immediate Window:

Sub xx()
Dim i As Long
Rnd -1
For i = 1 To 20000
    Debug.Print Rnd
Next i
End Sub

However, only the last 199 lines are stored there for me to copy and paste. How can I write the entire output to a text file instead?

Many thanks

Since your goal seems to be to get a lot of random numbers in the clipboard, you can do the following:

in the VBA editor under tools/references, add a reference to Microsoft Forms 2.0 Object Library and then use:

Sub RandToClip(n As Long)
    Dim clip As New DataObject
    Dim A As Variant
    Dim i As Long

    ReDim A(1 To n)
    Randomize

    For i = 1 To n
        A(i) = Rnd()
    Next i

    clip.SetText Join(A, vbCrLf)
    clip.PutInClipboard
End Sub

If you then eg enter RandToClip 20000 in your clipboard available for pasting somewhere else.

Answering your question: here is the basic function for that task. Make sure to add checks of whether file exists, not locked, etc. But take a look at the solution provided by John Coleman as it may be a better solution for your task.

Public Function WritetoTXT (Byval Text as String, byval FilePath as String)    
    Dim TextFile As Long
    TextFile = FreeFile
    Open Path For Append As TextFile
    Print #TextFile, Text
    Close TextFile
End Function

In your code:

Sub xx()
Dim i As Long
Rnd -1
For i = 1 To 20000
    WritetoTXT  Rnd, "your file path here"
Next
End Sub

Edit: As pointed out in comments to decrease overhead you can combine your code to the following:

Sub xx()
Dim i As Long
Rnd -1
Dim TextFile As Long
TextFile = FreeFile
Open "your file path here" For Append As TextFile
For i = 1 To 20000
    Print #TextFile,  Rnd
Next
Close TextFile
End Sub

You can easily write to a text file (file stream) by using a FileSystemObject . See example below for working code in a module:

Global fso As New FileSystemObject

Public Function GenRandomNumbers(ByVal n As Long) As String
    Dim i As Long
    Dim res As String
    Rnd -1
    For i = 1 To n
        res = res & CStr(Rnd()) & vbCrLf
    Next i
    GenRandomNumbers = res
End Function

Public Sub WriteRandomNumbers(ByVal n As Long, ByVal filename As String)
    Dim fs As TextStream
    Set fs = fso.CreateTextFile(filename, Overwrite:=True)
    fs.Write GenRandomNumbers(n)
    fs.Close
End Sub

In the immediate window you can write:

WriteRandomNumbers 20000, "Result.txt"

屏幕

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM