我只是想在用户选择的范围内选择随机行。但是,有时程序会选择特定范围之外的随机行。请参阅以下代码摘录:
Dim PopulationSelect As Range
Set PopulationSelect = Application.InputBox("Select range of cells in the population", Type:=8)
RandSample = Int(PopulationSelect.Rows.Count * Rnd +1)
Rows.(RandSample).EntireRow.Select
有谁知道这是为什么,以及如何解决它?
提前谢谢你。
答案 0 :(得分:5)
这是因为您的随机样本从1行到行数,而您的选择函数正在整张表上工作。
因此,如果populationSelect为A50:A51,您的兰特样本将为1或2,它将选择第1行或第2行
尝试
Sub test()
Dim PopulationSelect As Range
Set PopulationSelect = Application.InputBox("Select range of cells in the population", Type:=8)
RandSample = Int(PopulationSelect.Rows.Count * Rnd + 1)
PopulationSelect.Rows(RandSample).EntireRow.Select
End Sub
答案 1 :(得分:0)
考虑:
Sub qwerty()
Dim PopulationSelect As Range
Set PopulationSelect = Application.InputBox("Select range of cells in the population", Type:=8)
Dim nLastRow As Long
Dim nFirstRow As Long
Set r = PopulationSelect
nLastRow = r.Rows.Count + r.Row - 1
nFirstRow = r.Row
n = Application.WorksheetFunction.RandBetween(nFirstRow, nLastRow)
Cells(n, 1).EntireRow.Select
End Sub