循环通过指定范围内的单元格

编程入门 行业动态 更新时间:2024-10-28 13:27:16
本文介绍了循环通过指定范围内的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

循环通过指定范围内的单元格

本文发布于:2023-10-27 22:28:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534733.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   单元格

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!