【问题标题】:Subscript out of range error specifying the range of the loop of an array指定数组循环范围的下标超出范围错误
【发布时间】:2018-04-12 02:23:53
【问题描述】:

我的下标超出范围错误。

数组的循环范围肯定有问题,但我觉得范围已声明,并且我引用的相应最小值和最大值应该在各自数组中的相同位置。

我已经尝试过 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

【问题讨论】:

    标签: arrays vba loops outofrangeexception


    【解决方案1】:

    当您获取多个连续单元格区域的Value 属性时,您会得到一个二维数组值。如果您在监视窗口中检查MinAllocation,您会看到它类似于“Variant/Variant(1 to 36, 1 to 1)”

    要从二维数组中获取特定值,您需要为数组的两个维度指定下标。因此,MinAllocation(i) 将变为 MinAllocation(i, 1),以此类推其他数组。

    LBoundUBound 函数可以带一个参数来指定要检查的维度,但如果省略此参数,则会检查指定数组的第一个维度。这就是为什么对TrialAllocation 边界的检查没有失败并且似乎产生了合理的值

    【讨论】:

    • 谢谢。修复了问题。现在进入下一个!
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多