【发布时间】:2020-01-08 18:52:24
【问题描述】:
我正在编写一个 VBA 函数,它使用一个输入来确定包含其他输入的工作表。
不同的curvename,函数应该引用不同sheet中的数据。我的代码如下:
Public Function DFrate(mtmdate As Date, pmtdate As Date, curvename As String, colno As Integer) As Double
Dim yf As Double
Dim noday As Integer
Dim lastrow As Integer
Dim rate As Range
Dim tenor As Range
Dim DFinv As Double
Dim DFinv1 As Double
Dim DFinv2 As Double
noday = pmtdate - mtmdate
yf = noday / 360
MsgBox noday
ThisWorkbook.Sheets("HS_" & curvename).Activate
lastrow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
Set rate = ActiveSheet.Range(Cells(102, 3 + colno), Cells(lastrow, 3 + colno))
Set tenor = ActiveSheet.Range(Cells(102, 2), Cells(lastrow, 2))
If (noday <= tenor(1, 1)) Then
DFinv1 = (1 + rate(1, 1) / 100) ^ yf
DFinv2 = (1 + rate(2, 1) / 100) ^ yf
DFinv = DFinv1 + (noday - tenor(1, 1)) * (DFinv2 - DFinv1) / (tenor(2, 1) - tenor(1, 1))
MsgBox DFinv
End If
For k = 1 To lastrow
If (noday > tenor(k, 1) And noday <= tenor(k + 1, 1)) Then
DFinv1 = (1 + rate(k, 1) / 100) ^ (tenor(k, 1) / 360)
DFinv2 = (1 + rate(k + 1, 1) / 100) ^ (tenor(k + 1, 1) / 360)
DFinv = DFinv1 + (noday - tenor(k, 1)) * (DFinv2 - DFinv1) / (tenor(k + 1, 1) - tenor(k, 1))
Exit For
End If
Next k
DFrate = DFinv
End Function
我收到错误 #NAME? 甚至消息框“Msgbox noday”也不起作用。
有人可以告诉我应该在我的代码中更改什么吗?谢谢!
【问题讨论】:
-
将
Option Explicit放在代码表的顶部,然后重试。 -
您是否使用调试器单步执行您的代码以确定哪一行出现错误?另外,您确定
curvename(作为参数传入)有效,即("HS_" & curvename)是有效的工作表名称吗? -
@user10829321 我试过了,但它确实有效
-
@AlexP 是的,我检查了曲线名称是否有效。我想知道为什么连消息框都没有给出结果。