【问题标题】:How to feed looped WorksheetFunction calculation outputs into an array?如何将循环的 WorksheetFunction 计算输出输入数组?
【发布时间】:2021-05-13 02:08:56
【问题描述】:

这是我第一次在 Stack Overflow 上提问,希望清楚!

MC 宏的以下 VBA 代码不起作用。我正在尝试将循环计算(Excel beta.inv 统计公式)输入一个数组,并将完成的数组输出到工作表中进行检查。对此的推导可以很好地直接输出到工作表而不使用数组,但我更喜欢将数据输入数组以进行进一步计算(并尽量减少 VBA/工作表之间的来回以加快速度)。

代码:

Sub MC()
   Dim n As Integer
   Dim j As Integer
   Dim myArray As Variant
   Dim x as Integer

n = Range("L2").Value   
For j = 1 To n
   myArray(x) = WorksheetFunction.Beta_Inv(Range("l5").Value, Range("l3").Value, Range("l4").Value, 0, 1) 
   x = x + 1
Next j
       
'Print values to Immediate Window
For x = LBound(myArray) To UBound(myArray) 
  Debug.Print 
  myArray(x)
Next x

End Sub

其中单元格是 L2 = 100、L5 = RAND() 公式、L3 = 0.12 和 L4 = 0.17(顺便说一下,我会将 RAND() 公式嵌入到 VBA 中,并在我得到这个数组后将其从工作表中删除工作!!)

【问题讨论】:

    标签: arrays excel vba loops


    【解决方案1】:

    这个myArray(x) 是一个一维数组,但范围总是是二维的(即使它只有一行或一列,因为只有数组的第二个维度它才会获得方向无论是列还是行)。

    还需要使用DimReDim 定义数组的大小,否则数组没有大小:

    Dim myArray(1 To 10) As Variant 'only fixed numbers possible, no variables
    ReDim myArray(a To b) 'variable possible (ReDim can also be used without Dim)
    

    它应该如下所示:

    Sub MC()
        Dim n As Long
        n = Range("L2").Value
        If n < 1 Then Exit Sub 'prevent errors on next line n must be >=1
        
        'define an array that can be written into a range
        ReDim myArray(1 To n, 1 To 1) As Variant 'one column of data with n rows
        
        Dim j As Long
        For j = 1 To n
            myArray(j, 1) = WorksheetFunction.Beta_Inv(Range("l5").Value, Range("l3").Value, Range("l4").Value, 0, 1)
        Next j
        
        'Print values to Immediate Window
        Dim x As Long
        For x = LBound(myArray, 1) To UBound(myArray, 1)
            Debug.Print myArray(x, 1)
        Next x
        
        'can be written to a range like
        Range("A1", "A" & n).Value = myArray 'the range must have the same amount of rows/columns as the array or you lose data
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多