0

我编写了以下 VBA 代码来计算一些阈值,并在某一时刻将 Range 中的值放入数组中。但是,尽管我认为我已经定义了所有内容,但我收到“下标超出范围”错误。

还是 ValeursAction() As Variant 不正确?它应该是一个数组......我正在使用 Call Tri1(ValeursAction) 对其进行排序。

Option Explicit

Sub Performance()
Dim N As Long
Dim EnsembleActions As Range
Dim Nb_Actions As Integer
Dim Action As Range
Dim CoursAction As Range
Dim i As Integer
Dim SharpeRatio As Double
Dim TauxRf As Double
Dim RendsEcart As Double
Dim NomAction As String
Dim ValeursAction() As Variant
Dim NB As Integer

    With Worksheets("Actions")
        Nb_Actions = .Cells(1, Columns.Count).End(xlToLeft).Column
    End With

    With Worksheets("Actions")
        Set EnsembleActions = .Range(.Cells(2, 1), .Cells(.Rows.Count, Nb_Actions).End(xlUp))
    End With

    For Each Action In EnsembleActions.Columns
        i = i + 1
        Set CoursAction = Action

        TauxRf = Worksheets("Performance").Cells(2, 2).Value
        RendsEcart = WorksheetFunction.StDev(CoursAction)

         NB = WorksheetFunction.Count(CoursAction)

        'We place values from the range in a table
        With Worksheets("Actions")
            ValeursAction = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1)).Value
        End With

    'Sorting the array
    Call Tri1(ValeursAction)

    Dim alpha As Double
    Dim Var As Double

        alpha = Worksheets("Performance des fonds").Cells(3, 2).Value

        Var = ValeursAction(Int(NB * alpha))


        NomAction = Worksheets("Actions").Cells(1, i).Value

    With Worksheets("Performance")
        .Cells(4 + i, 1) = NomAction

        .Cells(4 + i, 2) = Var

    End With
Next Action

End Sub

Sub Tri1(plaga As Variant)
Dim ligne_Deb As Long
Dim ligne_Fin As Long

ligne_Deb = LBound(plaga)
ligne_Fin = UBound(plaga)

Dim i As Long, J As Long
Dim tmp As Long

For i = ligne_Deb To ligne_Fin - 1
    For J = ligne_Fin To i + 1 Step -1
        If plaga(J, 1) < plaga(J - 1, 1) Then
            tmp = plaga(J, 1)
            plaga(J, 1) = plaga(J - 1, 1)
            plaga(J - 1, 1) = tmp
        End If
    Next J
Next i

End Sub
4

1 回答 1

0

您正在自动标注尺寸的数组 (ValeursAction/plaga) 具有基于一的维度,而不是基于零的维度。但是对于这些行:

    If plaga(J, 1) < plaga(J - 1, 1) Then
        tmp = plaga(J, 1)
        plaga(J, 1) = plaga(J - 1, 1)
        plaga(J - 1, 1) = tmp
    End If

循环计数器J将递减到 1,因此J - 1为零,超出了数组的范围。

于 2013-05-05T18:12:26.527 回答