loop through cells in named range

后端 未结 3 2000
旧时难觅i
旧时难觅i 2020-12-20 20:17

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 creat

相关标签:
3条回答
  • 2020-12-20 20:53

    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 
    

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

    0 讨论(0)
  • 2020-12-20 20:53

    Try this, instead:

    Sub foreachtest2()
    Dim c As Range
    Range("A1:A3").Name = "Rng"
    For Each c In Range("Rng")
        MsgBox (c.Address)
    Next
    End Sub
    
    0 讨论(0)
  • 2020-12-20 21:03

    Set Rng =Range("A1:A3") is creating a range object, not a named range. This should work

    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
    

    If you want to create a Named Range called Rng then

    Range("A1:A3).Name="Rng"
    

    will create it or you can create and loop it like thsi

    Dim c As Range
    Range("a1:a3").Name = "rng"
    For Each c In Names("rng").RefersToRange
    MsgBox c.Address
    Next c
    
    0 讨论(0)
提交回复
热议问题