Switching from Range to Array and Back in a VBA Function

这一生的挚爱 提交于 2019-12-12 12:16:16

问题


There are a lot of questions, and a lot of responses dealing with Range/Array conversion in VBA. I haven't been able to find an answer that works, so I would really apreciate some help.

Below is what I'm trying to do:

    Function RangeToArrayToRange(inputRange As Range) As Range
        Dim inputArray As Variant
        inputArray = inputRange
        'operations on inputArray'
        '...'
        Dim outputRange As Range
        outputRange = inputArray
        Set RangeToArrayToRange = outputRange
    End Function

Thanks in advance for your help!


回答1:


If outputRange is the top-left cell of the range to be populated:

outputRange.Resize(Ubound(inputArray,1), _
                   Ubound(inputArray,2)).Value = inputArray

EDIT: I think this is what you want to do

Function RangeToArray(inputRange As Range) As Variant
   Dim inputArray As Variant
   inputArray = inputRange.Value

   'operations on inputArray
   '...'

   RangeToArray = inputArray
End Function

You can use this on a worksheet as a user-defined function (UDF)

  1. Select a range which is the same dimensions as the 'inputRange' (same number of rows/columns)
  2. Enter "=RangeToArray([yourinputrange])" in the formula bar and press Ctrl+Shift+Enter to enter the formula as an "array formula"

This assumes you're not altering the dimensions (upper/lower bounds) of inputArray in your function.



来源:https://stackoverflow.com/questions/11235517/switching-from-range-to-array-and-back-in-a-vba-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!