使用dynamic数组VBA确定斜率和截距

它已经有一段时间了,因为我已经在Excel VBA中使用数组,所以请原谅我…

我试图定义一个循环中确定的基于连续匹配单元格的dynamic数组。 我敢肯定,我的语法是错误的定义数组,我只是不知道如何。 难点在于我的数组由一列中的大约6个连续的行组成,再加上另一列中的另一个单元格组成。 有任何想法吗?

Sub calib_range() Dim instrument As Variant Dim calibrator As Variant Dim lastrow As Integer lastrow = ThisWorkbook.ActiveSheet.Range("b2").SpecialCells(xlCellTypeLastCell).Row For i = 4 To lastrow If Cells(i, 4) Like "MPC*" Then 'enter loop to determine length of MPC* array For x = i + 1 To lastrow If Cells(x, 4) = Cells(x - 1, 4) Then Else x = x - 1 Exit For End If Next x instrument = Array(Cells(i, 17), Range(Cells(i, 14), Cells(x, 14))) calibrator = Array(0, Range(Cells(i, 12), Cells(x, 12))) Slope = Application.WorksheetFunction.Slope(instrument, calibrator) Intercept = Application.WorksheetFunction.Intercept(instrument, calibrator) Cells(i, 22) = Slope Cells(i, 23) = Intercept End If Next i End Sub 

你的问题在这里:

  calibrator = Array(0, Range(Cells(i, 12), Cells(x, 12))) 

你不能这么做,因为VBA认为你的数组中有0和一个范围。 因此,你的数组由两个不同types的valuse组成。 这不是你所需要的。

在这里阅读更多关于如何初始化数组,这是很好的解释。

编辑:另外在上一行中,您只需制作一个范围数组。 什么会为你解决可能是这样的:

 Public Sub CheckArray() Dim my_array() As Double ReDim my_array(6) my_array(0) = Cells(1, 17) my_array(1) = Cells(2, 17) my_array(2) = Cells(3, 17) my_array(3) = Cells(4, 17) my_array(4) = Cells(5, 17) my_array(5) = Cells(6, 17) my_array(6) = Cells(7, 17) End Sub