title: Create a function to calculate mean of selected range in VBA
body: <p>I try to create a user defined function in Excel. In order to get the average number of any selected range, let's say the range of cells of H2 to H10, I create the following function. </p>
  
  <pre><code>Function avg(rng As Range) As Single
  
    Dim i%, nrow%, col%
    Dim sum As Single
  
    nrow = rng.Rows.Count
    col = rng.Column
    sum = 0
  
    For i = 1 To nrow
        sum = sum + Cells(i, col).Value
    Next i
  
    avg = sum / nrow
  
  End Function
  </code></pre>
  
  <p>However, when I enter the function in a cell and select the range of H1 to H10, the result gives a wrong average number. I don't even know how the number is calculated. 
  Thanks for the help.</p>