Excel VBA - 循环遍历范围并向数组添加值

问题描述 投票:0回答:2

我有一个函数可以接受像{variant, variant, variant}这样的数组作为参数。现在,它也可以接受像A1:A3这样的单元格作为相同的参数,但无法处理结果。

我认为我需要做的是循环遍历范围,并将每个值添加到数组中,例如:

  • A1:A3成为{Value in A1, Value in A2, Value in A3}
  • A1:B2成为{A1, A2, B1, B2}
  • A:A成为一个只有A列填充单元格的数组(同样的原则可以应用于上面的两个范围。只有填充的单元格被添加到数组中)

这样,我可以像处理用户在输入参数时自己输入数组一样处理结果。

如何在不事先知道范围大小的情况下做到这一点?我希望用户能够提供我可以转换为数组的任何大小/形状的范围。

IsArray()对于{variant, variant, variant}A1:A3的两个输入都返回true,所以然后我检查它是否是If TypeName(parameter) = "Range" Then的范围,但之后我在处理范围时遇到问题并且不知道如何将其转换为数组。

我尝试过研究,但我是VBA的新手,我认为我在搜索中使用了错误的术语。任何建议表示赞赏,谢谢!

更新以包含一些代码。请注意,这将是该功能首先要做的事情。后来的代码与问题无关,除非后面的代码需要处理一组值。

If IsArray(my_values) Then

    'If it's a Range then I need to get the values of each cell and put them into an array.
    'If they passed an array like `{1,1,1}`, move on and process the array
    If TypeName(my_values) = "Range" Then
        Dim rows_count As Long
        Dim columns_count As Long
        Dim cells_count As Long

        'Just testing, not sure if necessary
        rows_count = my_values.rows.Count
        columns_count = my_values.columns.Count
        cells_count = rows_count * columns_count
        'Or just cells_count = my_values.Cells.Count

        'Need to loop through each cell in the range now and put the values into an array

    End If

    'Continue processing the array
excel vba
2个回答
1
投票

考虑:

Public Function RangeToArray(rng As Range) As Variant
    Dim i As Long, r As Range
    ReDim arr(1 To rng.Count)

    i = 1
    For Each r In rng
        arr(i) = r.Value
        i = i + 1
     Next r

    RangeToArray = arr
End Function

enter image description here

举个例子。

当我们在工作表中输入数组时,我们必须确保在行(8)中点亮足够的单元以容纳8单元输入范围。

该方法可以适用于处理任何尺寸或形状的输入范围。


0
投票

鉴于你的参数是变量,并且你总是希望函数的输出是一个数组,并且你将有一个输入作为参数,可以是一个范围,一个数组常量,或一个非数组常量,以下函数将始终输出一个数组(即使输入是非数组常量)

Option Explicit
Function makeArray(myArray As Variant) As Variant
    Select Case IsArray(myArray)
        Case True
            makeArray = myArray
        Case False
            makeArray = Array(myArray)
    End Select
End Function

在范围的情况下,输出将是2D数组,其中d1表示行,d2表示列。

否则输出将具有与输入相同的尺寸。如果输入不是数组,则输出将是具有一维和一个值的数组。

© www.soinside.com 2019 - 2024. All rights reserved.