我正在尝试编写一个循环遍历一个范围内的所有单元格的代码。最终我想做一些比较复杂的事情,但是由于我遇到麻烦,我决定创建一些简短的测试程序。第一个示例工作正常,但第二个(具有命名范围)不会(给出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.
更多推荐
循环通过指定范围内的单元格
发布评论