Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How store a range from excel into a Range variable?

Tags:

excel

vba

I am reading some cells of excel using VBA.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, _
dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer)

    Dim dataTable as Range
    dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, _
    dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    getData = dataTable

EndFunction

It throws an error, object variable or with block variable not set. How take this range in a variable? Please guide me.

like image 487
Priyank Thakkar Avatar asked Sep 02 '12 13:09

Priyank Thakkar


People also ask

How do you assign a range of cells to a variable in VBA?

Therefore, we need to use the “Set” keyword to set the reference. The variable “Rng” refers to the range of cells from A2 to B10. So, instead of writing “Range(“A2:B10″))” every time, we can write the word “Rng.” In the next line, mention the variable name “Rng” and put a dot to see the magic.

How do I copy a range to another range in excel?

Copy a Cell or Range to Another WorksheetFirst, define the range or the cell that you want to copy. Next, type a dot (.) and select the copy method from the list of properties and methods. Here you'll get an intellisense to define the destination of the cell copied.

How do you store a range in an array?

Steps to Add a Range into an Array in VBA First, you need to declare a dynamic array using the variant data type. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well. After that, assign the range where you have value to the array.


1 Answers

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

like image 184
enderland Avatar answered Sep 24 '22 17:09

enderland