14

我有一个名为“X”的命名范围,它有 1000 行,我想动态地将其减少到 100。

我尝试过Range("X").Resize(100,1).Resize(-900,0)但当我通过从范围下拉菜单中选择范围来签入 Excel 时,似乎都没有改变命名范围的大小。我究竟做错了什么?

4

2 回答 2

32

假设您有一个名为“myRange”的命名范围。如果你这样做:

Dim r As Range
Set r = Range("myRange")
Debug.Print r.Resize(10, 1).Address

你的意思是:我有这个范围rmyRange将其设置为与其初始状态匹配。然后调整大小r到别的东西。你所做的是你调整了大小r,而不是myRange.

要调整命名范围的大小,您需要执行以下操作:

Dim wb As Workbook
Dim nr As Name

Set wb = ActiveWorkbook
Set nr = wb.Names.Item("myRange")

' give an absolute reference:
nr.RefersTo = "=Sheet1!$C$1:$C$9"

' or, resize relative to old reference:
With nr
    .RefersTo = .RefersToRange.Resize(100, 1)
End With
于 2012-06-14T12:28:59.653 回答
2

感谢您的贡献。根据您的帮助,我能够将这段代码放在一起来调整范围的大小并将 n 行从一个数组发布到它。

Sub PostArrayLinesToRange(ByVal rngName As String, ByRef arr As Variant, ByVal r As Long)
    Dim wb As Workbook
    Dim rng As Range
    Dim nr As Name          'Variable to change named range size definition

    Set wb = ThisWorkbook
    Set rng = Range(rngName)

    rng.Clear
    Set nr = wb.Names.item(rngName)
    With nr
        .RefersTo = .RefersToRange.Resize(r, UBound(arr, 2))
    End With
    Set rng = Range(rngName)
    rng = arr
    Erase arr
    Set nr = Nothing
    Set rng = Nothing
    Set wb = Nothing
End Sub
于 2015-01-30T18:57:46.883 回答