2016-10-20 244 views
1

它已經有一段時間我用Excel中VBA數組所以請原諒我...使用動態數組VBA確定斜率和截距

我試圖定義基於是連續的匹配單元的動態數組循環確定。我確定我的語法是錯誤的,因爲我不知道如何定義數組。難點在於我的數組由一列中的大約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 
+3

你有'細胞(X,4)=細胞(X - 1,4)Then',並直接轉到'Else' - 你丟失碼?爲什麼有'If'語句這樣寫? – BruceWayne

+0

@BruceWayne它可能是兩個單元格中的值是相似的,因此它不會去其他地方。 – Vityata

+1

@Vityata - 肯定 - 只是好奇,爲什麼不把它設置爲'If Cells()<> Cells Then // x = x-1 // Exit For'。 (對於凱爾的切向問題,我不認爲這是問題的一部分,只是我注意到的一部分。) – BruceWayne

回答

1

你的問題是在這裏:

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

你不允許這樣做,因爲VBA認爲您的數組中你得到一個0和範圍。因此,你的數組由兩種不同類型的valuse組成。這不是你需要的。

閱讀here更多關於如何初始化數組,這很好解釋。

編輯: 也在上一行中,您只需製作一組範圍。什麼會制定出你大概是這樣的:

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 
+1

那麼' calibrator = Array(0,Range(Cells(i,12).Value,Cells(x,12).Value))'? –

+0

這會給出一個結果,但OP正試圖將整個範圍(具有多個單元格)+零置入一個數組中。 – Vityata

相關問題