excel - 如何在 Excel 中使用 VBA 函数输出填充 n 个单元格?

标签 excel vba

我需要在给定区域中重复生成 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将其作为数组公式输入:

enter image description here

关于excel - 如何在 Excel 中使用 VBA 函数输出填充 n 个单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790235/

相关文章:

excel - 在露天阅读pdf文件

excel - 无法在 Excel VBA 中使用 .End(xlDown) 分配范围?

javascript - VBA填充多行PDF?

vba - 使用 native 代码中的值列表填充 VBA 数组

excel - 让 Excel 函数影响 'other' 单元格

vba - Excel VBA 运行时错误 '424' 删除行时需要对象

c#、Excel + csv : how to get the correct encoding?

c# - 通过 Web 服务将数据从 Sql Server 移动到 Excel

excel - RangeToHTML 和单元格中的图像

excel - 如果单元格中添加了某些内容,则添加 "Now"