[英]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.