我需要在给定区域中重复生成 n 个随机点。 因此,我想创建一个填充 n x 2 个单元格(n 个点的 x 和 y 坐标)的 Excel 函数。 n 是函数的参数。
Function generateForest(number) As Variant
Dim position(1 To number, 2) As Single
For i = 1 To number
x(i, 1) = Rnd()
x(i, 2) = Rnd()
Next i
generateForest = positions
End Function
最佳答案
您不能在 Dim
语句中使用诸如 number
之类的变量,但可以将其与 ReDim
一起使用。对代码进行以下调整即可:
Function generateForest(number As Long) As Variant
Randomize
Dim i As Long
Dim position As Variant
ReDim position(1 To number, 1 To 2)
For i = 1 To number
position(i, 1) = Rnd()
position(i, 2) = Rnd()
Next i
generateForest = position
End Function
要使用,请选择例如A1:B10
在电子表格中,输入公式
=generateForest(10)
然后使用Ctrl+Shift+Enter
将其作为数组公式输入:
关于excel - 如何在 Excel 中使用 VBA 函数输出填充 n 个单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790235/