4

Can someone please help me understand the below code.

Set items = Range("A2:A" & Range("A1").End(xlDown).Row)

What I dont understand is how the range is set up? Which area is covered by A2:A and A1 according to this? I know if I have a table like below this code works

enter image description here

But if I change the table location to following how do I change the example code? enter image description here

4

2 回答 2

2

哪个区域被覆盖A2:AA1根据这个?

代码不是试图覆盖A2:A也不A1

在这段代码中:

Set items = Range("A2:A" & Range("A1").End(xlDown).Row)

该部分"A2:A" & Range("A1").End(xlDown).Row组合为 的一个参数Range()

所以整个部分以"A2:A" & "4", 或结尾A2:A4

鉴于此,对于您的第二个屏幕截图,您可以使用类似的过程:

  1. C5:C从中选择C5(这是“项目”列的第一个“数据”单元格);
  2. &连接字符串;
  3. Range("C4")选择C4(这是“项目”列的“标题”单元格);
  4. Range("C4").End(xlDown)C从 开始向下选择到最后一个非空单元格C4
  5. Range("C4").End(xlDown).Row返回所选单元格的行号(在本例中为 7);

因此,对于您的第二个屏幕截图,您得到:

Set items = Range("C5:C" & Range("C4").End(xlDown).Row)
于 2013-06-17T09:54:07.773 回答
1

在这里,代码被分成几部分,在消息框中,您将能够看到发生了什么,HTH。

Sub test()

    ' Range.End Property:
    ' Returns a Range object that represents the cell at the end of the region that contains the source range.
    ' Equivalent to pressing END+DOWN ARROW.
    Dim endXlDown As Range
    Set endXlDown = Range("A1").End(xlDown)
    MsgBox "endXlDown.Address = " & endXlDown.Address

    Dim endXlDownRow As Long
    endXlDownRow = endXlDown.Row
    MsgBox "endXlDown.Row = " & endXlDown.Row

    Dim targetAddress As String
    targetAddress = "A2:A" & endXlDownRow
    MsgBox "targetAddress = " & targetAddress

    Dim items As Range
    Set items = Range(targetAddress)
    MsgBox "items.Address = " & items.Address

    items.Select ' and here you see the resulting range as selection
End Sub
于 2013-06-17T09:27:30.643 回答