【发布时间】: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