Excel 尝试更改范围时,RowIndex的范围不起作用

Excel 尝试更改范围时,RowIndex的范围不起作用,excel,vba,Excel,Vba,我尝试使用以下代码选择随机行: Sub Randomization() Dim nNumber As Integer, nRowIndex As Integer 'Generate a random number nNumber = Int(Rnd() * (11 - 2 + 1)) + 2 'Go through the list For nRowIndex = 2 To 11 If nRowIndex = nNumber Then MsgBox &

我尝试使用以下代码选择随机行:

Sub Randomization()
  Dim nNumber As Integer, nRowIndex As Integer

  'Generate a random number
  nNumber = Int(Rnd() * (11 - 2 + 1)) + 2

  'Go through the list
  For nRowIndex = 2 To 11
    If nRowIndex = nNumber Then
      MsgBox "The number is " & Cells(nRowIndex, 1).Value
    End If
  Next nRowIndex
End Sub

但是,当我尝试将nRowIndex的
范围替换为,比如说,
31到42时,宏不起作用。

我们可以很容易地找到
Rnd
功能的描述:

VBA Rnd函数生成大于或等于0且小于1的随机数

这意味着
Int(Rnd()*(11-2+1))+2
正在生成从包含2到排除12的随机数,因此,如果将循环边界更改为31和42,它将永远不会匹配随机生成的数,因此看起来什么也不会发生

修改后的代码为:

Sub Randomization()
  ' Integer occupies the same space in memory as Long, so we Long should be used instead
  Dim nNumber As Long, nRowIndex As Long, lowerBound As Long, upperBound as Long

  lowerBound = 2
  upperBound = 11
  ' Generate a random number from given range
  nNumber = Int(Rnd() * (upperBound - lowerBound)) + lowerBound

  'Go through the list
  For nRowIndex = lowerBound To upperBound - 1
    If nRowIndex = nNumber Then
      MsgBox "The number is " & Cells(nRowIndex, 1).Value
    End If
  Next nRowIndex
End Sub
您可以尝试以下方法:

Sub Randomization()
  Dim nNumber As Integer, nRowIndex As Integer

  'Generate a random number
  nNumber = Application.WorksheetFunction.RandBetween(31, 42) 'Change here (Need to be same)

  'Go through the list
  For nRowIndex = 31 To 42 'Change here (Need to be same)
    If nRowIndex = nNumber Then
      MsgBox "The number is " & Cells(nRowIndex, 1).Value
    End If
  Next nRowIndex
End Sub