2017-07-13 23 views
0

我正在嘗試查找循環的最大值。首先,我有兩個隨機數組,我想找到這兩個數組的相關係數。然後,我想多次計算它的「I3」單元。之後,我想編寫一個代碼,該代碼可以從該計算中找到最大相關係數。我寫了下面的代碼,但沒有奏效。使用VBA查找循環的最大值

Sub Macro1() 

Dim i As Long 
For i = 1 To Range("I3") 
    Calculate 
Next 

DMax = Application.WorksheetFunction.Max("A2") 
Range("I4").Value = DMax 

End Sub 

任何幫助表示讚賞。

+0

什麼是範圍(「I3」),你是指這個單元格中的值還是...?你想通過在單個單元上調用'Max'實現什麼?最大值爲一個值返回該值... –

+0

範圍(「I3」)指的是此單元格中的值。我想要計算與此值一樣多的係數。我想用代碼找到這些值的最大值。 – OykuA

回答

1

您的最大功能需要一個適當的參數。只需輸入「A2」在VBA中不起作用。嘗試:

DMax = Application.WorksheetFunction.Max(Range("A2")) 

這會給你的陣列A2的MAX-價值。但請記住,由單個單元格組成的範圍的最大值始終是單元格值。


如果要計算所有迭代的最大值,你應該在每次迭代中使用的最大功能(內部for循環),並保存它的價值。在接下來的每次迭代中,如果新的最大值大於舊值,則應該覆蓋最大值。就像這樣:

Sub Macro1() 

Dim i As Long 
DMax = 0 
For i = 1 To Range("I3") 
    Calculate 
    DMax2 = Application.WorksheetFunction.Max(Range(...)) 
    If DMax2 > DMax Then DMax = DMax2 
Next i 

Range("I4").Value = DMax 

這會給你所有迭代範圍(...)的最大值。

+0

是的,這是我的問題。你有關於我如何解決它的想法? – OykuA

+0

編輯我的答案。 – Andi

+0

謝謝,但我不明白我應該寫什麼,而不是「範圍(.....)」。 – OykuA

0

我幾乎無法理解您的代碼,但解決方案將被激活循環。假設您有兩組數字:A2Cells(2, 1))到I2Cells(2, 7))和A3Cells(3, 1))到I3Cells(3, 7))。你想計算偏相關,並找到它的最大值。

For i = 1 To 7 
    For j = 1 To i 
     'Calculate the correlation 
    Next j 
    'here you have partial coefficient and you can compare it, 
    'if it is greater than previous one then save it and store 
Next i 
0
For i = 1 To Range("I3").value 'to calculate from 1 to the value in that cell 

什麼,我會推薦你​​的問題。

For i = 1 To 10 ' loop 10 times 
    For j = 1 To i ' here it will allow you to check your stuff multiple times before moving on to the next value 
    arr1(i) = arr2(j) ' see if your array match 
    Next j 

Next i