我需要找到由RND -1生成的前20,000个随机数。我写了下面的代码,它允许我在立即窗口中看到这些数字:
Sub xx()
Dim i As Long
Rnd -1
For i = 1 To 20000
Debug.Print Rnd
Next i
End Sub
但是,只有最后199行存储在那里供我复制和粘贴。如何将整个输出写入文本文件?
非常感谢
答案 0 :(得分:1)
由于您的目标似乎是在剪贴板中获取大量随机数,因此您可以执行以下操作:
在工具/引用下的VBA编辑器中,添加对Microsoft Forms 2.0 Object Library
的引用,然后使用:
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
如果你那么,例如在剪贴板中输入RandToClip 20000
可用于粘贴到其他位置。
答案 1 :(得分:1)
回答你的问题:这是该任务的基本功能。确保添加文件是否存在,未锁定等的检查。但请查看John Coleman提供的解决方案,因为它可能是您的任务的更好解决方案。
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
在您的代码中:
Sub xx()
Dim i As Long
Rnd -1
For i = 1 To 20000
WritetoTXT Rnd, "your file path here"
Next
End Sub
修改强> 正如评论中指出的那样,为了减少开销,您可以将代码组合到以下内容中:
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
答案 2 :(得分:1)
您可以使用FileSystemObject
轻松写入文本文件(文件流)。有关模块中的工作代码,请参阅下面的示例:
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
在即时窗口中,您可以写:
WriteRandomNumbers 20000, "Result.txt"