'H' Column is the year data column, 'I' Column is the month data column, 'D' Column is the 10-year bond yield we want to calculate the monthly volatility.This is another improved code for this question, please help me. The return is still #NAME. Thanks the answer from @Comintern. According to @Comintern's advice, I've revised the code. In the name manager, 'Yr' refers to the column of the year (H3: H3696), 'M' refers to the column of the month (I3: I3696), 'C_10' refers to the original yield data of China 10 Year Treasury Bond.
Right now, I want to get the monthly volatility of the yield.
Function Volatility(n As Variant) As Variant
'this function uses to calculate volatility of a bond yield
'"n" is the number of data/date we need to calculate
'please manage the data name in the name manager of formulas
Dim i As Integer, dnum As Integer, mnum As Integer, vectornum As Integer
'dnum count day number, mnum count month number
Dim Result(), TempSave() As Variant
Dim Yr, M As Range
vectornum = Int(n / 20) + 1
ReDim Result(vectornum) As Variant
Yr = ActiveWorkbook.Names("Yr").Value
M = ActiveWorkbook.Names("M").Value
Bond = ActiveWorkbook.Names("C_10").Value
For i = 1 To n
If Yr(i) = Yr(i + 1) And M(i) = M(i + 1) Then
dnum = dnum + 1
ReDim Preserve TempSave(1 To dnum)
TempSave(dnum) = Bond(i)
'this is the temporary data container for the same month bond yield
Else
TempSave(dnum + 1) = Bond(i)
'because there is a gap between two month, so, we add the last 'same month bond yield' back
dnum = 0
mnum = mnum + 1
Result(mnum) = Application.WorksheetFunction.StDev_S(TempSave)
End If
Next i
Volatility = Result
End Function