在 VBA 中引用命名范围内的单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25827925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:55:58  来源:igfitidea点击:

Referencing Cells within Named Range in VBA

excelvbaexcel-vba

提问by Matias Scardia

I'd like to know if its possible to use Cells(r, c) within a named range in VBA. Ex.: I have named range "Test" to be A1:B5 and I am working on a Macro that loops through this range, however I'd like to avoid explicit declarations of ranges as much as possible, so sheet manipulation can be as easier as possible.

我想知道是否可以在 VBA 的命名范围内使用 Cells(r, c)。例如:我已将范围“Test”命名为 A1:B5 并且我正在研究一个循环遍历此范围的宏,但是我想尽可能避免范围的显式声明,因此工作表操作可以是尽可能容易。

In case what I said wasnt possible, I basically need to be able to loop/write through cells in the named ranges, if there is another approach for this I'd be more than glad to get a suggestion.

如果我所说的不可能,我基本上需要能够循环/写入命名范围内的单元格,如果有另一种方法,我会很高兴得到建议。

Thanks!

谢谢!

回答by KekuSemau

Sure, you can simply use e. g.

当然,你可以简单地使用例如

Worksheets("name").Range("Test").Cells(r, c)

Worksheets("name").Range("Test").Cells(r, c)

and

Dim c As Range
For Each c In Worksheets("Name").Range("Test").Cells
    Debug.Print c.Address
Next

回答by Matias Scardia

I figured it out with a bit more of research In case anyoone drops by wondering this:

我通过更多的研究来解决这个问题,以防万一有人想知道这个:

Sub test()
    dim r1 as Range
    set r1 = Range("NamedRange")

    f = r1.row
    l = Range("NamedRange").Row + Range("NamedRange").Rows.Count - 1

    Do while (Cells(f,1) <> "" and f <= l
        'Run code
    Loop
end sub