如何将计算分配给函数



我正在尝试创建一个UDF来最小化计算中的数据行。我想创建一个名为 Rent_Rate 的变量并将其设置为等于 Base_year_rent * ((1 + Rent_escalator(^Compound_period(,而不是包括特定单元格引用的声明计算,以便电子表格中的公式显示为"= Rent_Rate * 单位(静态单元格引用(">

我尝试定义变量并将每个变量设置为我希望(在单独的工作表上(引用的参考单元格。

Public Function Rent_Rate(Base_year_rent As Long, Rent_escalator As Long, Compound_period As Long, Rent_Rate As Long) As Long
    Base_year_rent = SH_Assumptions.Cells("C11")
    Rent_escalator = SH_Assumptions.Cells("C12")
    Compound_period = Year(Range(ActiveCell, ActiveCell.End(xlUp)).Select) - Year(SH_Assumptions.Cells("C4"))
    Rent_Rate = Base_year_rent * ((1 + Rent_escalator) ^ Compound_period)
End Function

我希望输出将是一个特定值,等于输入到被引用单元格中的值。

首先 - Excel 中的函数需要有括号,例如 =Rent_Rate()

您可以通过设置具有所需名称的命名范围来绕过它,该范围调用您的UDF(例如,名为RentRate的命名范围,它=Rent_Rate()

下一个问题是你已经给出了你的 UDF 3 参数,但没有向他们传递任何内容。 事实上,你会立即覆盖它们 - 只是Dim变量!

Public Function Rent_Rate() AS Long
    Dim Base_year_rent As Long, Rent_escalator As Long, Compound_period As Long, Rent_Rate As Long
    Base_year_rent = SH_Assumptions.Cells("C11").Value
    Rent_escalator = SH_Assumptions.Cells("C12").Value
    'What is this abomination supposed to do???
    Compound_period = Year(Range(ActiveCell, ActiveCell.End(xlUp)).Select) - Year(SH_Assumptions.Cells("C4"))
    Rent_Rate = Base_year_rent * ((1 + Rent_escalator) ^ Compound_period)
End Function

但是,您在这里仍然有一个大问题 - 为什么要使用 ActiveCellSelect特别是在UDF中,您应该避免使用Select。 如果尝试使用调用函数的单元格,请查找Application.Caller

最新更新