【问题标题】:Excel VBA - Loop through range and add values to arrayExcel VBA - 遍历范围并将值添加到数组
【发布时间】:2017-12-17 10:04:13
【问题描述】:

我有一个函数可以接受像{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

【问题讨论】:

  • 一个Range 对象有一个Rows 属性,它有一个Count 属性(Columns 也是如此)所以你可以从1 To rng.Rows.Count 循环。它还有一个Cells 属性,因此您可以从1 To rng.Cells.Count 循环。或者你可以做一个For Each anotherRange In rng.Cells,等等。有很多方法可以做到这一点。
  • 帮我们帮你; 发布您当前的代码
  • 我对上一个问题的回答中的第一行将 Range 转换为数组 If TypeOf my_values Is Range Then my_values = my_values

标签: excel vba


【解决方案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

举个例子。

当我们在工作表中对函数进行数组输入时,我们必须确保在行 (8) 中点亮足够多的单元格以适应 8 单元格的输入范围。

这种方法可以适应任何大小或形状的输入范围。

【讨论】:

    【解决方案2】:

    假设您的参数是变体,并且您将始终希望函数的输出是一个数组,并且您将有一个输入作为参数,它可以是一个范围、一个数组常量或一个非-array 常量,下面的函数会一直输出一个数组(即使输入的是非数组常量)

    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
    

    在范围的情况下,输出将是一个二维数组,其中 d1 代表行,d2 代表列。

    否则输出将与输入具有相同的维度。 如果输入不是一个数组,那么输出就是一个一维一值的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多