0

以下效果很好(感谢这个社区的慷慨帮助!)

    Function RangeToArrayToRange(inputRange as Range) As Variant
            Dim inputArray As Variant
            inputArray = inputRange
            RangeToArrayToRange = inputArray
    End Function

此功能将完美地将输入范围复制到输出。但是,当我对 inputArray 进行一些操作时,数组看起来很完美,但在 Excel 中,只有数组的第一个值会打印到所有单元格。在这个例子中,我从一些输入字符串中解析出一个数字。

输入范围:

ABC=1X:2Y 
ABCD=10X:20Y
ABCDE=100X:200Y

代码:

    Function RangeToArrayToRange(inputRange As Range) As Variant

        Dim inputHeight As Integer
        inputHeight = inputRange.Count

        Dim inputArray As Variant
        inputArray = inputRange

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

        Dim currentInput As String
        Dim currentInputAsInt As Integer
        Dim i As Integer

        For i = 1 To inputHeight

            currentInput = inputArray(i, 1)
            currentInput = Right(currentInput, (Len(currentInput) - Application.WorksheetFunction.Find("=", currentInput))) 
            'splits out everything left of the "="
            currentInput = Right(currentInput, (Len(currentInput) - Application.WorksheetFunction.Find(":", currentInput)))
            'splits out everything to the right of the ":"
            currentInput = Left(currentInput, Len(currentInput) - 1) 
            'split out the letter to allow int casting
            currentInputAsInt = CInt(currentInput)
            'cast to int
            strippedArray(i) = currentInputAsInt
            'saved

        Next i

        RangeToArrayToRange = strippedArray
    End Function

预期输出:

1
10
100

实际输出:

1
1
1

通过调试器运行,strippedArray 分别在 strippedArray(1)/(2)/(3) 位置包含 Variant/Integer 值 1,10,100。问题是,据我所知,我在 Excel 中输入的数组范围仅包含 strippedArray(1)。

谢谢!

4

1 回答 1

4

如果您要输出回 Excel 工作表/范围,则您strippedArray的数组需要是二维的(我假设您将其作为数组公式运行)。进行以下更改:

ReDim strippedArray(1 To inputHeight, 1 To 1)
...
strippedArray(i, 1) = currentInputAsInt
于 2012-06-28T14:46:44.437 回答