循环通过指定范围内的单元格 [英] loop through cells in named range

查看:230
本文介绍了循环通过指定范围内的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个循环遍历一个范围内的所有单元格的代码。最终我想做一些比较复杂的事情,但是由于我遇到麻烦,我决定创建一些简短的测试程序。第一个示例工作正常,但第二个(具有命名范围)不会(给出Object Range of Object_Global Failed错误消息)。关于我做错什么的任何想法?我真的很想用一个命名范围做这个...谢谢!

I am trying to write code that will loop through all cells in a range. Eventually I want to do something more complicated, but since I was having trouble I decided to create some short test programs. The first example works fine but the second (with a named range) doesn't (gives a "Method Range of Object_Global Failed" error message). Any ideas as to what I'm doing wrong? I'd really like to do this with a named range... Thanks!

作品:

Sub foreachtest()
Dim c As Range
For Each c In Range("A1:A3")
    MsgBox (c.Address)
Next
End Sub

无效:

Sub foreachtest2()
Dim c As Range    
Dim Rng As Range
Set Rng = Range("A1:A3")
For Each c In Range("Rng")
    MsgBox (c.Address)
Next
End Sub


推荐答案

要调整第二个代码,您需要认识到您的范围rng现在是一个代表范围的变量,并将其视为:

To adjust your second code, you need to recognize that your range rng is now a variable representing a range and treat it as such:

Sub foreachtest2() 
Dim c As Range     
Dim Rng As Range 
Set Rng = Range("A1:A3") 
For Each c In rng
    MsgBox (c.Address) 
Next 
End Sub 

警告:大多数情况下,如果您可以避免循环,代码将更快g通过范围。

Warning: most of the time, your code will be faster if you can avoid looping through the range.

这篇关于循环通过指定范围内的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆