我编写了以下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
答案 0 :(得分: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
为零,这超出了数组的范围。