How store a range from excel into a Range variable?

后端 未结 5 1432
时光说笑
时光说笑 2021-01-04 12:15

I am reading some cells of excel using VBA.

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


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 13:01

    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.

提交回复
热议问题