excelruntime-errorrangevba

How do you reference Ranges in Excel VBA?


I have a named range in Excel that has some data I want to process in a subroutine or function, however I'm having a hard time figuring out how to reference individual parts of the range. I'm trying to use the Cells function, but it doesn't seem to be working.

Here is a snippet of my code:

Sub sub1()
x = Range("Test")

For Each i In x
    v = x.Cells(i, 1)
    calculate(v)
Next i

End Sub

As of right now, the named range "Test" is named for A1:A18 and the calculate function hasn't been written. Using the debug tools in VBA, the program throws an error at the v = x.Cells(i,1) line: "Run-time error '424': Object required"

There seems to be something obvious I'm missing. Perhaps there's a way to convert a named range to an array?


Solution

  • Everything is in Siddharth Rout answer ; I'll just go into more detailed explanation.

    The flaw is that x is undeclared, therefore VB uses a Variant. You need x to be a Range type, so you can refer to its Cells property. Therefore you should declare it so.

    Insert Dim x as Range as first line of sub1. You will then have to use the Set keyword to assign to x : Set x = Range("test")

    Set is the syntax used to assign objects.

    Also, the Cells property is the default property of Range. Therefore it is not required to write it explicity.

    For each i in x 
    

    assigns to i a Range object which is the i'th cell of range x. So you can apply calculate on i.

    Now one last thing : Calculate can be applied to a single cell or to a Range. Therefore, x.Calculate would work (whithout the need for a loop).

    This gives :

    Sub sub1()
      Dim x as Range
      Dim i as Range
      Set x = Range("Test")
    
      For Each i In x
          i.Calculate
      Next i
    
    End Sub
    

    or simpler:

    Sub sub1()
      Dim x as Range
      Set x = Range("Test")
    
      x.Calculate
    
    End Sub
    

    if "Calculate" is a user-function :

    Sub sub1()
      Dim x as Range
      Dim i as Range
      Set x = Range("Test")
    
      For Each i In x
          Call CalculateMyPurpose(i)
      Next i
    
    End Sub
    
    Sub CalculateMyPurpose(myCell as Range)
      'Do something on myCelll
    End Sub
    

    NB : I would suggest you declare all variables. This will make sure they have the type you want them to. To enforce variable declarations, write Option Explicit as 1st line of the module.