首页 > 解决方案 > 尝试更改范围时,RowIndex 的范围不起作用

问题描述

我正在尝试使用此代码选择随机行:

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

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

标签: excelvba

解决方案


你可以试试这个:

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

推荐阅读