[英]Subscript out of range error specifying the range of the loop of an array
我的下標超出范圍錯誤。
數組循環的范圍一定存在問題,但是我感覺范圍已聲明,並且我要引用的對應的min和max應該在各自數組中的相同位置。
我嘗試了Redim(但可能不正確),並明確指定了數組的尺寸(1到36),但又一次可能不正確。
下標超出范圍錯誤發生在For j = MinAllocation(i) To MaxAllocation(i)
。
'declare variables
Dim Sharpe As Variant
Dim CurrentAllocation As Variant
Dim MaxAllocation As Variant
Dim MinAllocation As Variant
Dim TrialAllocation As Variant
Dim BestAllocation As Variant
inc = Sheet1.Range("B59").Value
'populate variables
CurrentAllocation = Sheet1.Range("S2:S37").Value
MaxAllocation = Sheet1.Range("N2:N37").Value
MinAllocation = Sheet1.Range("P2:P37").Value
TrialAllocation = Sheet1.Range("G2:G37").Value
'Populate trial range with current allocation and populate current Sharpe Ratio
Sheet1.Range("G2:G37").Value = CurrentAllocation
Sharpe = Sheet1.Range("B53").Value
'loop through each cell in the array
Dim i As Long
Dim j As Long
For i = LBound(TrialAllocation) To UBound(TrialAllocation)
'loop through each possible integer in current cell from corresponding minimum to corresponding maximum
For j = MinAllocation(i) To MaxAllocation(i) Step inc
TrialAllocation(i) = j
'check the total of the trial array and populate worksheet with trial data if the total of the array equals 100 and update timer
Total = WorksheetFunction.Sum(TrialAllocation)
If Total = 100 Then
Sheet1.Range("G2:G37").Value = TrialAllocation
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
Sheet1.Range("Z42").Value = (SecondsElapsed / 86400)
'store the trial array if the Sharpe Ratio is greater than the previous highest Sharpe Ratio and further constraints are met (B57 = 0)
If Sheet1.Range("B53").Value > Sharpe And Sheet1.Range("B57").Value = 0
Then
Sharpe = Sheet1.Range("B53").Value
BestAllocation = Sheet1.Range("g2:g37").Value
End If
End If
Next Step inc
Next
當您采用多個連續像元的范圍的Value
屬性時,將獲得一個二維數組。 如果在監視窗口中檢查MinAllocation
,您將看到類似“ Variant / Variant(1到MinAllocation
到1)”的內容。
要從2D數組獲取特定值,您需要為數組的兩個維度指定下標。 因此,對於其他數組, MinAllocation(i)
將變為MinAllocation(i, 1)
,依此類推。
LBound
和UBound
函數可以使用參數來指定要檢查的維,但是如果省略此維,則會檢查指定數組的第一個維。 這就是為什么對TrialAllocation
的邊界檢查沒有失敗並且似乎產生了合理的值的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.