我有一个函数可以接受数组作为{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}
对于和的两个输入都返回 true A1:A3
,所以然后我检查它是否是一个范围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
Run Code Online (Sandbox Code Playgroud)
考虑:
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
Run Code Online (Sandbox Code Playgroud)
举个例子。
当我们在工作表中对函数进行数组输入时,我们必须确保在行(8)中高亮显示足够的单元格以容纳 8 个单元格的输入范围。
这种方法可以适应处理任何尺寸或形状的输入范围。
归档时间: |
|
查看次数: |
21580 次 |
最近记录: |