简体   繁体   English

Excel VBA范围选择

[英]Excel VBA range select

I have a macro in which I need to select the range R2:last row in sheet . 我有一个宏,我需要在其中选择范围R2:last row in sheet However the last row in my sheet might be blank in column R . 但是,我工作表中的最后一行在R列中可能为空白。 At the moment I am using this 目前我正在使用

Dim t As Range
Set t = Range("R2", Range("R1000").End(xlUp))

For Each Cell In t
    If IsEmpty(Cell) Then
        Cell.Activate
        ActiveCell.Value = "To Be Picked Up"
    End If
Next

However if the last row has a blank in column R then it gets ignored. 但是,如果最后一行R列中有空白,则它将被忽略。 I am hoping to pull the range using column A , as the last row of data always has column A . 我希望使用A列拉动范围,因为数据的最后一行始终具有A列。 So something like, 所以像

Dim t As Range
Set t = Range("R2", Range("A1000").End(xlUp).ActiveCell.Offset(0, 17))

For Each Cell In t
    If IsEmpty(Cell) Then
        Cell.Activate
        ActiveCell.Value = "To Be Picked Up"
    End If
Next

It seems so simple but I'm sure im missing something stupid. 看起来很简单,但我敢肯定我会错过一些愚蠢的东西。 Any help or alternative methods would be helpful thank you. 任何帮助或替代方法将对您有所帮助,谢谢。

This should do the trick in one line: 这应该在一行中完成:

Sub SO()     
    Range("R2:R" & Range("A" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeBlanks).Value = "To Be Picked Up"
End Sub 

But in answer to your question specifically 但是专门回答你的问题

Set t = Range("R2:R" & Range("A" & Rows.Count).End(xlUp).Row)  

The Range() method will accept a string as an argument to obtain a range.So we can build this string any way we want: Range()方法将接受字符串作为获取Range()的参数,因此我们可以根据需要构建此字符串:

"A1000"                '// A1000
"A" & 1000             '// A1000
"A" & "10" & "00"      '// A1000
"A" & CStr(1001 - 1)   '// A1000
  • "A" & Rows.Count will return A65536 or A1048576 depending on the type of worksheet. 根据工作表的类型, "A" & Rows.Count A65536将返回A65536A1048576

  • Range("A1048576").End(xlUp) as you know, will retrieve the last cell in that area, or the first cell in the next area on the direction specified. 如您所知, Range("A1048576").End(xlUp)将在指定方向上检索该区域中的最后一个单元格,或下一个区域中的第一个单元格。

  • Range("A1048576").End(xlUp).Row will return the row number of that cell (let's say it's A1000 for argument's sake) so the return value is 1000 . Range("A1048576").End(xlUp).Row将返回该单元格的行号(假设参数是A1000),因此返回值为1000

  • "R2:R" & Range("A" & Rows.Count).End(xlUp).Row therefore makes the string R2:R1000 . "R2:R" & Range("A" & Rows.Count).End(xlUp).Row使字符串R2:R1000

  • So finally, Range("R2:R" & Range("A" & Rows.Count).End(xlUp).Row) is the same as Range("R2:R1000") 因此,最后, Range("R2:R" & Range("A" & Rows.Count).End(xlUp).Row)Range("R2:R1000")

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

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