vba VBA在选择范围内选择随机行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25212330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:09:50  来源:igfitidea点击:

VBA Select Random Row In Range of Select

excelvbaexcel-vbauser-input

提问by Kyle Snell

I am simply trying to select a random row within a user selected range. However, at times the program will select a random row outside of the specific range. See code excerpt below:

我只是想在用户选择的范围内选择一个随机行。但是,有时程序会选择特定范围之外的随机行。请参阅下面的代码摘录:

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

Does anyone know why this is, and how to fix it?

有谁知道这是为什么,以及如何解决?

Thank you in advance.

先感谢您。

回答by gtwebb

It's because your random sample is going from 1 to the number of rows and your select function is working on the entire sheet.

这是因为您的随机样本从 1 到行数,并且您的 select 函数正在处理整个工作表。

So if populationSelect is A50:A51 your rand sample would be 1 or 2 and it would select row 1 or 2

因此,如果populationSelect 是A50:A51,您的rand 样本将是1 或2,它会选择第1 行或第2 行

Try

尝试

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

回答by Gary's Student

Consider:

考虑:

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