How to assign an Excel Range to a 2D array?

后端 未结 3 806
心在旅途
心在旅途 2020-12-19 16:30

Could you please say- how a Excel Range(\"G2:AA1000\") can be assigned to a 2D array? If possible how to return back that 2D array to the same range after performing some op

3条回答
  •  清酒与你
    2020-12-19 16:38

    Here's a worked-out example of reading a range of data from a worksheet, operating on the array, and then writing it back out to the same worksheet.

        Sub RangeArray()
    
        Dim Rng As Range
        Dim Arr()
        Dim ArrItem
        Dim i As Long, j As Long
        Dim rUB as Long, cUB as Long
    
         Set Rng = Worksheets("Sheet1").Range("A1:G19")
        rUB = Rng.Rows.Count    'Row upper bound
        cUB = Rng.Columns.Count  ' Column upper bound
    
        ReDim Arr(1 To rUB, 1 To cUB)
    
       'Read worksheet range into array
        For i = 1 To rUB
           For j = 1 to cUB
              Arr(i, j) = Rng.Cells(i, j).Value
           Next
        Next
    
       'Do something to array 
        For i = 1 To rUB
           For j = 1 To cUB
              If i <> j Then
                 Arr(i, j) = Arr(i, j) / (i * j)
              End If
           Next
        Next
    
       'Write array back to worksheet
        Set Rng = Worksheets("Sheet1").Range("I1")
        For i = 1 To rUB
           For j = 1 To cUB
              Rng.Offset(i - 1, j - 1).Value = Arr(i, j)
           Next
        Next
    
        End Sub
    

提交回复
热议问题