title: how to calculate current moving average from current element-lag to current element in VBA excel
body: <p>I have a spike detection function which takes a data range and a lag i.e. moving average window as input.  Please let me know how to calculate moving average.</p>
  <pre><code>spikedetection(data, lag)
  ' data is the range , lag is the window for moving average
  
  Dim X() As Integer
  Dim Y() As Double
  Dim Z() As Double
  Dim ce As Double
  Dim avg, sum_squared, moddata As Double
  Dim st As Integer
  nrows = data.Cells.Count
  sum = 0
  csum = 0
  For element = 1 To nrows
      ce = data.Cells(element)
      If element &gt; lag Then
              Y(currentmoving) = 
  ' how to calculate current moving average from current element-lag to current element.
         
      End If
      
  Next element
  End Function
  
  </code></pre>