简体   繁体   中英

Assigning an array value to a variable in VBA causes my UDF to exit

I can't seem to figure out why this UDF is exiting on the currentInput = inputArray(i) . Here is the relevant code:

Function OrderRange(inputRange As Range) As Variant

    Dim length As Integer
    inputHeight = inputRange.Count

    Dim inputArray As Variant
    inputArray = inputRange

    Dim strippedArray() As Variant
    ReDim strippedArray(0 To (inputHeight - 1))

    Dim currentInput As String

    Dim i As Integer

    For i = 0 To (inputHeight - 1)

        currentInput = inputArray(i)
        '...computations on currentInput...'
        strippedArray(i) = currentInput
    Next i
    OrderRange = strippedArray
End Function

The debugger reaches currentInput = inputArray(i) but once I move to the next line, the function terminates and a #VALUE! error is entered into the cell I call the function from. I know this is a specific question, but I'm sure it's a general issue and I'll edit this original post to reflect what the general problem is.

Edit: This is an issue regarding assignment of a range to a variant array.

Variant arrays created by setting them equal to ranges have two dimensions even if they are only one column, or row, wide. So if you call the function with A1:A10 you'll get a 10 * 1 array. Also the lower bound of the dimensions will be one, not zero. So you'd have to do something like:

For i = 1 To (inputHeight)
    currentInput = inputArray(i, 1)

Also you should use Option Explicit so that you're reminded to declare all variables. InputHeight is never declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM