使用范围偏移设置范围

时间:2017-02-14 05:34:09

标签: excel vba range cells

我想建立一个范围来做工作。我能够返回上次使用的单元格的行和列索引,但是如何将其包含在命名范围内?

numRows = sht.Cells(Rows.Count, 2).End(xlUp).Row
numColumns = sht.Cells(1, Columns.Count).End(xlToLeft).Column

Set endRange = sht.Cells(numRows, numColumns)

Set workRange = sht.Range("B1", Cells(numRows, numColumns)?

3 个答案:

答案 0 :(得分:1)

试试这个

Set workRange = sht.Range("B1", Cells(numRows, numColumns))
ActiveWorkbook.Names.Add Name:="myName", RefersToR1C1:=workRange.Address

答案 1 :(得分:1)

With sht
    numRows = .Cells(.Rows.Count, 2).End(xlUp).Row
    numColumns = .Cells(1, .Columns.Count).End(xlToLeft).Column

    Set endRange = .Cells(numRows, numColumns)

    Set workRange = .Range("B1", endRange)

    .Parent.Names.Add Name:="myName", RefersToR1C1:=workRange.Address
End With

答案 2 :(得分:1)

这应该有效:

With Sheets("Sheet1")
        Set rng = .Range("B1:" & .Cells(numRows, numColumns).Address)
        ThisWorkbook.Names.Add Name:="workRange", RefersTo:=rng
End With

请注意,您可以多次运行它,它只会简单地覆盖现有的命名变量“workRange”。

要将其构建为一系列非连续范围,您只需使用上述内容,但使用逗号将其他范围附加到字符串上,如下所示:

Set rng=.Range("B1:C2,E4:F6,G2:" & Cells(numRows,numColumns).Address)