简体   繁体   English

Range.Rows.Count和我可以通过将行索引传递给Excel 2010 VBA中的Range.Rows返回的行之间的不匹配

[英]Mismatch between Range.Rows.Count and the rows I can return by passing row index to Range.Rows in Excel 2010 VBA

I have a worksheet with 600 rows each representing a student. 我有一个包含600行的工作表,每行代表一个学生。 I have a User Form which displays one student at a time. 我有一个用户表格,一次显示一位学生。 The Next/Previous buttons on the form trigger a GetStudent Sub which takes one argument, the current row index. 窗体上的“下一个/上一个”按钮触发一个GetStudent Sub,该子接受一个参数,即当前行索引。 I don't want to work with all 600 rows at a time so I create a range with A1:Z10 syntax like this in the GetStudent Sub. 我不想一次处理所有600行,因此我在GetStudent Sub中使用A1:Z10语法创建了一个范围。 This is done programmatically, but for clarity I've put a literal value in the code sample: 这是通过编程方式完成的,但为清楚起见,我在代码示例中添加了文字值:

Dim ds As Range, w As Worksheet, currentRow As Range
Set w = ActiveWorkbook.Worksheets("students_sheet")
Set ds = w.Range("A4:Z5")

If I do 如果我做

Debug.Print ds.Rows.Count

I get the expected 2, but when I pass an index to ds.Rows() 我得到了预期的2,但是当我将索引传递给ds.Rows()时

Set currentRow = ds.Rows(rowIndex)

I get the next row in the worksheet all the way through the 600 rows in the worksheet not only the 2 rows in the specified range. 我一直在工作表中一直到达工作表中的600行,而不仅仅是指定范围内的2行。 The range is not limited to the 2 rows indicated by the Rows.Count property. 范围不限于Rows.Count属性指示的2行。 Can anyone help me figure out what I'm doing wrong? 谁能帮我弄清楚我在做什么错?

The Rows property is relative to the range you call it on, and not bounded by the range itself. Rows属性是对于您调用它的范围的,而不受范围本身的限制。

So, when ds is set to A4:Z5 and you call ds.Rows(rowIndex) then you will get 因此,当ds设置为A4:Z5并调用ds.Rows(rowIndex)您将获得

rowIndex     Range
1            A4:Z4
10           A13:Z13
0            A3:Z3
-2           A1:Z1
-3           error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM