gpt4 book ai didi

vba - 创建生成唯一随机数的excel VBA宏

转载 作者:行者123 更新时间:2023-12-04 21:10:02 25 4
gpt4 key购买 nike

我想创建一个宏,它基本上会根据用户输入返回随机数,但是,我希望每个输出都是唯一的(这就是 randbetween() 函数不适用于此的原因)。以下是我到目前为止的内容,但我不断收到引用错误。我从网上找到的几个不同示例中将这段代码拼接在一起,因此以任何方式进行优化也将不胜感激。

代码:

Sub RandomSample()
Dim cell As Range
Dim rng As Range
Low = 1
High = Application.InputBox("Enter population total", Type:=1)
Sample = Application.InputBox("Enter the Sample Size", Type:=8)
Set rng = Application.Range(ActiveCell, ActiveCell.Offset(Sample, 0))
For Each cell In rng.Cells
If WorksheetFunction.CountA(Selection) = (High - Low + 1) Then Exit For
Do
rndNumber = Int((High - Low + 1) * Rnd() + Low)
Loop Until Selection.Cells.Find(rndNumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
cell.Value = rndNumber
Next
End Sub

错误窗口:
Error image

最佳答案

尝试这个

Sub RandomSample()
Dim cell As Range
Dim Sample As Range 'declare Sample as Range
Low = 1
High = Application.InputBox("Enter population total", Type:=1)
Set Sample = Application.InputBox("Enter the Sample Size", Type:=8)
For Each cell In Sample 'use sample in loop
If WorksheetFunction.CountA(Sample) = (High - Low + 1) Then Exit For
Do
rndnumber = Int((High - Low + 1) * Rnd() + Low)
Loop Until Sample.Cells.Find(rndnumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
cell.Value = rndnumber
Next
End Sub

编辑:
Sub RandomSample()
Dim cell As Range
Dim rng As Range
Dim High As Long, Sample As Long
Low = 1
High = Application.InputBox("Enter population total", Type:=1)
Sample = Application.InputBox("Enter the Sample Size", Type:=1)
Set rng = Application.Range(ActiveCell, ActiveCell.Offset(Sample, 0))
For Each cell In rng.Cells
If WorksheetFunction.CountA(rng) = (High - Low + 1) Then Exit For
Do
rndNumber = Int((High - Low + 1) * Rnd() + Low)
Loop Until rng.Cells.Find(rndNumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
cell.Value = rndNumber
Next
End Sub

关于vba - 创建生成唯一随机数的excel VBA宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46222822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com