2013-05-05 101 views
0

我已经编写了下列VBA代码来计算某个阈值,并且在某一点上,我将范围中的值放入数组中。但是,我认为我已经定义了所有内容,但出现“下标超出范围”错误。使用范围和数组在VBA过程中下标超出范围错误

或者是ValeursAction()作为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 
+0

哪一行产生错误? – RBarryYoung 2013-05-05 17:59:07

+0

您是否将基于0的对象与基于1的对象混淆?很容易忘记哪些是哪个。 – 2013-05-05 18:11:50

+0

我不这么认为......这个代码在我添加数组ValeursAction之前工作得很好...... – seigna 2013-05-05 18:12:45

回答

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是零,这是你的阵列的束缚的。

+0

所以我应该把Option Base 1放在第一个子? – seigna 2013-05-05 18:15:36

+0

它不会改善任何东西..仍然有相同的错误 – seigna 2013-05-05 18:23:20

+0

不,您需要更改上面的代码,以便它停止尝试访问零。 – RBarryYoung 2013-05-05 19:46:06