VBA Select Random Row In Range of Select

自作多情 提交于 2019-12-11 09:07:59

问题


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.


回答1:


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.

So if populationSelect is A50:A51 your rand sample would be 1 or 2 and it would select row 1 or 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



回答2:


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


来源:https://stackoverflow.com/questions/25212330/vba-select-random-row-in-range-of-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!