突出显示范围中的随机行

时间:2017-12-20 09:29:20

标签: excel vba random

我正在尝试创建一个宏,按下按钮会突出显示选区中的随机行。我有以下代码(基于@gtwebb向@Kyle Snell慷慨提供的答案):

Sub SelectRandom()
Dim mrg As Worksheet
Set mrg = ActiveWorkbook.Sheets("Merged")

Dim PopulationSelect As Range
Set PopulationSelect = mrg.Range("A" & Rows.Count).End(xlUp)


RandSample = Int(PopulationSelect.Rows.Count * Rnd + 1)
PopulationSelect.Rows(RandSample).EntireRow.Interior.Color = RGB(255, 255, 153)

End Sub

现在在工作表上我有一个标题占用范围(“A1:L5”)所以我需要代码随机选择并突出显示包含数据的标题下面任何行的一行。我该怎么做呢?代码仅选择并突出显示当前包含数据的最后一行。

1 个答案:

答案 0 :(得分:1)

请试试下面的代码。

Sub SelectRandom()
    Dim mrg As Worksheet
    Dim Rand As Long
    Dim PopulationSelect As Range

    Set mrg = ActiveWorkbook.Sheets("Merged")

    'Define your start row below (instead of 6)
    Rand = Application.WorksheetFunction.RandBetween(6, mrg.Range("A" & Rows.Count).End(xlUp).Row)
    mrg.Rows(Rand).EntireRow.Interior.Color = RGB(255, 255, 153)

End Sub