[VBA]For-Next문의 이해

반복 횟수만큼 실행문을 반복할 때 사용한다.

Option Explicit

Function GetMean(Score() As Double) As Double
Dim L As Long
Dim U As Long
Dim i As Long
Dim sum As Double

L = LBound(Score, 1)
U = UBound(Score, 1)

sum = 0
For i = L To U
sum = sum + Score(i)
Next i

GetMean = sum / (U – L + 1)
End Function

이상은 평균을 구하는 함수이다. 다음은 분산(Variance)를 구하는 함수이다.

Function GetVariance(Score() As Double) As Double
Dim L As Long
Dim U As Long
Dim i As Long
Dim sum As Double
Dim avg As Double

L = LBound(Score, 1)
U = UBound(Score, 1)

avg = GetMean(Score)

sum = 0
For i = L To U
sum = sum + (Score(i) – avg) ^ 2
Next i

GetVariance = sum / (U – L + 1)
End Function

다음은 표준편차를 구하는 함수이다.

Function GetStandardError(Score() As Double) As Double
Dim L As Long
Dim U As Long
Dim i As Long
Dim sum As Double
Dim avg As Double

L = LBound(Score, 1)
U = UBound(Score, 1)

avg = GetMean(Score)

sum = 0
For i = L To U
sum = sum + (Score(i) * Score(i))
Next i

GetStandardError = (sum / (U – L + 1)) – (avg * avg)
End Function

위에는 오류 코드(버그)가 숨겨 있다. 잘 찾아보아 보세요.

Print Friendly, PDF & Email