作为一个UDF,这应该写成如下(或类似的东西):
Public Function MorBlend(Table1 As Variant, Blend As Double, Table2 As Variant) As Variant
'Table3 needs to be a two dimensional array, with the first dimension
'representing rows in the result, and the second dimension representing
'columns in the result
Dim Table3(1 To 106, 1 To 1) As Variant
Dim Age As Integer
For Age = 0 To 105
Table3(Age + 1, 1) = Round(Table1(Age + 1) * Blend / 1000000 + Table2(Age + 1) * (1 - Blend) / 1000000, 6) * 1000000
Next
MorBlend = Table3
End Function
然后可以在单元格 C1:C106 中使用此函数(例如)并作为数组公式输入(按 Ctrl-Shift-Enter kbd> 输入公式)为
=MorBlend(A1:A106,.25,B1:B106)
注意:如果您想允许从 0 岁到 105 岁的死亡率(或其他)表,您需要修改代码以使用输入数组的UBound。上面的代码是硬编码的,期望正好是 106 速率,并且不包括对不是传入的情况的错误检查。
如果您不打算将该函数用作 UDF,则某些数组尺寸标注的限制可以较少 - 即您可以将数组尺寸标注为从 0 而不是 1 开始,并且您不需要有一个二维数组。
Public Function MorBlend(Table1 As Variant, Blend As Double, Table2 As Variant) As Variant
Dim Table3() As Variant
ReDim Table3(LBound(Table1) To UBound(Table1)) As Variant
Dim Age As Integer
For Age = LBound(Table1) To UBound(Table1)
Table3(Age) = Round(Table1(Age) * Blend / 1000000 + Table2(Age) * (1 - Blend) / 1000000, 6) * 1000000
Next
MorBlend = Table3
End Function
此版本的代码可用于以下程序:
Sub Main
Range("D2:D107") = Application.Transpose(Mor("71 GAM (50M/50F)"))
End Sub
Public Function Mor(Table As String) As Variant
Dim Tbl_71GAM_M50F50 As Variant
Dim Tbl_71GAM_M As Variant
Dim Tbl_71GAM_F As Variant
'Load tables from Excel ranges (e.g. "Tbl_716AM_M" may be the name of
' B2:B107, and "Tbl_716AM_F" may be the name of C2:C107)
Tbl_71GAM_M = Application.Transpose(Range("Tbl_716AM_M"))
Tbl_71GAM_F = Application.Transpose(Range("Tbl_716AM_F"))
'Create a merged table
Tbl_71GAM_M50F50 = MorBlend(Tbl_71GAM_M, 0.5, Tbl_71GAM_F)
If Table = "71 GAM Male" Then Mor = Tbl_71GAM_M
If Table = "71 GAM Female" Then Mor = Tbl_71GAM_F
If Table = "71 GAM (50M/50F)" Then Mor = Tbl_71GAM_M50F50
End Function
或者,如果您想将 Mor 作为数组 UDF 调用,您可以使用以下代码
Public Function Mor(Table As String) As Variant
Dim Tbl_71GAM_M50F50 As Variant
Dim Tbl_71GAM_M As Variant
Dim Tbl_71GAM_F As Variant
'Load tables from Excel ranges (e.g. "Tbl_716AM_M" may be the name of
' B2:B107, and "Tbl_716AM_F" may be the name of C2:C107)
Tbl_71GAM_M = Application.Transpose(Range("Tbl_716AM_M"))
Tbl_71GAM_F = Application.Transpose(Range("Tbl_716AM_F"))
'Create a merged table
Tbl_71GAM_M50F50 = MorBlend(Tbl_71GAM_M, 0.5, Tbl_71GAM_F)
If Table = "71 GAM Male" Then Mor = Application.Transpose(Tbl_71GAM_M)
If Table = "71 GAM Female" Then Mor = Application.Transpose(Tbl_71GAM_F)
If Table = "71 GAM (50M/50F)" Then Mor = Application.Transpose(Tbl_71GAM_M50F50)
End Function
然后在单元格 D2:D107 中输入一个数组公式,例如 `=Mor("71 GAM (50M/50F)")。
(可能性太多,展示它们的空间太小了。)