VBA Custom Function Working in immediate window but not in Worksheet? Throwing #VALUE Error

163 views Asked by At

I'm trying to get exp. Moving Average of Some quote. I build a custom function to retrieve it in my sheet. when I'm trying to execute in cell, it throws #Value Error. But when I execute it in immediate window it runs perfectly. even I've tried to make it volatile. I'm not sure why this happening. Below is my VBA code:

Option Explicit

 Function ExpMovingAverage9(Symbol As String, FromDate As String, ToDate As String) As Variant
    Application.Volatile
    Dim ws As Worksheet
    Dim tblInv As ListObject
    Dim SymbolTable As ListObject
    Dim FromDateTable As ListObject
    Dim ToDateTable As ListObject
    Dim Last As Long
    Dim LastValue As Variant
    Set ws = ThisWorkbook.Worksheets("AARTIIND")
    Set tblInv = ws.ListObjects("ChartData")
    Set SymbolTable = ws.ListObjects("Symbol")
    Set FromDateTable = ws.ListObjects("FromDate")
    Set ToDateTable = ws.ListObjects("ToDate")
    SymbolTable.DataBodyRange.Cells(1, 1) = Symbol
    FromDateTable.DataBodyRange.Cells(1, 1) = FromDate
    ToDateTable.DataBodyRange.Cells(1, 1) = ToDate
    tblInv.QueryTable.Refresh
    Application.CalculateUntilAsyncQueriesDone
    Last = tblInv.Range.Rows(tblInv.Range.Rows.Count).Row
    LastValue = Range("G" & (Last - 1)).Value
    ExpMovingAverage9 = LastValue
End Function
0

There are 0 answers