如何在 VBA 中使用 IRR() 函数
How to use IRR() function in VBA
我正在尝试使用 VBA 中的 IRR 函数。 IRR() 在 Excel 中运行良好。正如我在 VBA 中编写的,
a = Array(3, 4, 5)
b = IRR(a, 0.1)
它抱怨 "Compile error: Type mismatch: array or user-defined type expected"。让我傻眼的是一个 IS 数组。怎么了?
我根据 Pieter Geerkens 重写了函数如下:
option base 1
Function trial()
Dim a(2) As Double, b As Double
a(1) = 1.2
a(2) = 3.4
b = IRR(a(), 0.1)
End Function
我收到错误消息:运行-时间错误“5”:过程调用或参数无效。
不,a
不是数组;它是“一个包含数组的变体”。 VBA 不是 C-type 语言,并且没有那些具有的初始化程序。试试这个代码:
Dim a(0 To 2) As Double
a(0) = -3#
a(1) = 4#
a(2) = 5#
Dim v As Double: v = irr(a(), 0.1)
您需要应用 Excel Application object, the WorksheetFunction object 或两者。此外,数组中的第一个元素应为负数。
Dim a As Variant, b As Double
a = Array(-6, 4, 5)
b = Application.IRR(a, 0.1)
Debug.Print b
b = WorksheetFunction.IRR(a, 0.1)
Debug.Print b
b = Application.WorksheetFunction.IRR(a, 0.1)
Debug.Print b
VBE 的即时结果 window ([ctrl]+G)
0.305158649140883
0.305158649140883
0.305158649140883
我正在尝试使用 VBA 中的 IRR 函数。 IRR() 在 Excel 中运行良好。正如我在 VBA 中编写的,
a = Array(3, 4, 5)
b = IRR(a, 0.1)
它抱怨 "Compile error: Type mismatch: array or user-defined type expected"。让我傻眼的是一个 IS 数组。怎么了?
我根据 Pieter Geerkens 重写了函数如下:
option base 1
Function trial()
Dim a(2) As Double, b As Double
a(1) = 1.2
a(2) = 3.4
b = IRR(a(), 0.1)
End Function
我收到错误消息:运行-时间错误“5”:过程调用或参数无效。
不,a
不是数组;它是“一个包含数组的变体”。 VBA 不是 C-type 语言,并且没有那些具有的初始化程序。试试这个代码:
Dim a(0 To 2) As Double
a(0) = -3#
a(1) = 4#
a(2) = 5#
Dim v As Double: v = irr(a(), 0.1)
您需要应用 Excel Application object, the WorksheetFunction object 或两者。此外,数组中的第一个元素应为负数。
Dim a As Variant, b As Double
a = Array(-6, 4, 5)
b = Application.IRR(a, 0.1)
Debug.Print b
b = WorksheetFunction.IRR(a, 0.1)
Debug.Print b
b = Application.WorksheetFunction.IRR(a, 0.1)
Debug.Print b
VBE 的即时结果 window ([ctrl]+G)
0.305158649140883
0.305158649140883
0.305158649140883