创builddate列表并避免variables未设置(VBA错误91)

我有五张表中的某些股票的财务数据,并试图创build一个计算给定范围的指数移动平均线的函数。

[列(1)=date; 栏(2)=收盘价格]

这个函数的参数是计算EMA所需要的天数,和一个整数kol来并行计算几个EMA(现在不用)。 这是我的代码到目前为止:

 Public Function MME(Lmme As Double, kol As Long) Dim Cmme As Range Dim Todate, rcell As Range Dim alpha, period, Udate, i, j, k As Long Dim Ustock As String Dim wsDest As Worksheet Udate = ThisWorkbook.Worksheets("UserForm").Range("B2").Value period = ThisWorkbook.Worksheets("UserForm").Range("B3").Value Ustock = ThisWorkbook.Worksheets("UserForm").Range("B4").Value ' MsgBox (Udate) Set wsDest = ThisWorkbook.Sheets(Ustock) wsDest.Activate With wsDest.Range("A2:A392") Set Todate = Cells.Find(What:=Udate, _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Todate Is Nothing Then MsgBox ("todate wasn't found") Else End If End With i = Todate.Row j = i + period k = i - Lmme Set Cmme = Range(Cells(i, 9 + kol), Cells(j, 9 + kol)) alpha = (2 / (Lmme + 1)) With Cmme For Each rcell In Cmme If rcell.Row <> i Then rcell.Formula = "=B" & rcell.Row & "*" & alpha & "+I" & rcell.Row - 1 & "*" & 1 - alpha & ""\ Else: rcell.Formula = "=AVERAGE(B" & k & ":B" & i & " ) " End If Next rcell End With End Function 

我在一张单独的纸上创build了一个列表,允许用户在2008年select一个date,另一个让他select一个股票。 所以我确实设置了新的variables来完成这个技巧,但是它不起作用。

UsactionUSdateUperiod是存储用户select的值的名称范围。 但是我在set = period得到“错误91或对象需要”。

我真的希望EMA仅在特定时间段内计算,从所选date开始计算。 编辑:我更新了我有最新版本的代码。 endate EDIT2上仍然有一个错误91:代码已更新。 我不明白为什么没有finddate。 在工作表用户窗体上,用户select的date是“B2”( USdate )。 这是在一般的格式,但与查找function的CDate应该被认为是一个date是正确的? 我试着用date格式,它没有改变任何东西…

编辑3:感谢Branislav我设法通过切换每个date到通用格式来查找作品。 由于查找工作,无论如何,使其使用date格式工作? 这样用户可以看到实际的date,而不是相关的整数。

另一个问题:如何绕过Cells.Formula直接在VBA中运行,并使得它在Excel中的公式栏中的公式显示,除了范围内的SMA和EMA操作的结果?

ToDate已经是一个范围

 Set Endate = Todate.Row + period 

另外,在你到达这一点之前,你使用.Find()来设置ToDate 。 由于完全有可能会有人input无效的date或者没有数据的date,所以我强烈build议添加:

 if ToDate is Nothing then 'do some date not found stuff here else 'do your date found stuff here End If 

您可能还需要考虑将LookIn:=xlFormulasLookIn:=xlValues因为我相信您正在查找单元格值,而不是单元格公式。