具有公式阵列VBA的动态范围

时间:2018-04-23 11:12:12

标签: vba dynamic excel-formula

我对VBA中的公式数组有疑问。我试图在一系列单元格上运行一个公式,而我从中选取数据的范围正在循环中变化。我得到了#14; FormulaArray不能使用Range类"的错误。我试图将公式分成几部分,但没有运气。我猜它与我如何引用细胞有关?当公式使用R1C1样式时,它很有效,但在我使用Cells时则不行。请注意,代码使用的是另一张工作表而不是实际工作表ws2

   Private Sub CommandButton4_Click()
       Dim ws2 As Worksheet
       Dim y_out As Range
       Dim y_in As Range
       Dim x_in As Range
       Dim x_out As Range
       Dim length As Long

       Set ws2 = Sheets("Sheet2")
       For i = 1 To datasets

                length = ws2.Cells(ws2.Rows.Count, i + 4).End(xlUp).Row

                Set y_out = ws2.Range(ws2.Cells(2, i * 4 + 2), ws2.Cells(length, i * 4 + 2))
                Set y_in = ws2.Range(ws2.Cells(2, i * 4 + 4), ws2.Cells(length, i * 4 + 4))
                Set x_in = ws2.Range(ws2.Cells(2, i * 4 + 3), ws2.Cells(length, i * 4 + 3))
                Set x_out = ws2.Range(ws2.Cells(2, i * 4 + 1), ws2.Cells(length, i * 4 + 1))

                y_out.FormulaArray = "=loess(x_in,y_in,x_out,50)"

                FormulaArray = "=loess(RC[1]:R[490]C[1],RC[2]:R[490]C[2],RC[-1]:R[490]C[-1],50)"


       Next i

    End Sub

2 个答案:

答案 0 :(得分:0)

x_iny_in等不是命名范围,但您尝试使用它们,就好像它们一样。

这提供了2个解决方案:使它们命名为Ranged(并相应地更改)或使用它们的.Address

y_out.FormulaArray = "=loess(" & x_in.Address & ", " & y_in.Address & ", " & x_out.Address & " , 50)"

答案 1 :(得分:0)

似乎我可以使用R1C1表示法和更少的代码行来解决它。由于R1C1符号相对于活动单元格起作用,我只需要使用length将变量" & length & "添加到公式中。它起作用是因为y_out在每次迭代后都会更改位置。

Private Sub CommandButton4_Click()

   Dim ws2 As Worksheet
   Dim y_out As Range
   Dim y_in As Range
   Dim x_in As Range
   Dim x_out As Range
   Dim length As Long

   Set ws2 = Sheets("Sheet2")
   For i = 1 To datasets

            length = ws2.Cells(ws2.Rows.Count, i + 4).End(xlUp).Row

            Set y_out = ws2.Range(ws2.Cells(2, i * 4 + 2), ws2.Cells(length, i * 4 + 2))


            y_out.FormulaArray = "=loess(RC[1]:R[" & length & "]C[1],RC[2]:R[" & length & "]C[2],RC[-1]:R[" & length & "]C[-1],50)"


   Next i

End Sub