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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With