Guest User

Untitled

a guest
Feb 22nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. Option Explicit ' Forces declaration of variables/types
  2.  
  3.  
  4. Sub standard_deviation()
  5. ' Declare all variables, as required by enabling of Option Explicit
  6. Dim row_count As Byte, i As Byte ' Row count equates to number of measurements (-1 if header). If the row count might be longer than 255 you can change them to Integer or Long, dependent on your needs
  7. Dim data_col_index As Byte, target_col_index As Byte ' Column Number that contains the data and COlumn number to populate results
  8. Dim sum As Double, xbar As Double ' Sum of all measures and Mean, respectively
  9. Dim squared_diff As Double, variance As Double, std_dev As Double ' Squared Difference, Variance and Standard Deviation, respectively
  10. Dim WS As Worksheet ' Worksheet object, should be constant, hence all caps, but Objects can't be compiled as constants in VBA
  11. Dim rng As Range ' Range/Cell object
  12.  
  13. 'Dim spread As Double
  14. ' Application Logic:
  15. ' Instantiate squared difference variable as it is a running total
  16. squared_diff = 0
  17. ' Set col_index to the column that contains data and target column as dest. Change as needed
  18. data_col_index = 1: target_col_index = 2
  19. ' Set the WS constant to the first sheet in workbook. Change as needed
  20. Set WS = ThisWorkbook.Sheets(1)
  21. ' Get row count in column(col_index). Change col_index as needed
  22. row_count = WS.Cells(Rows.Count, data_col_index).End(-4162).Row
  23. ' Get sum of all measures
  24. sum = Application.WorksheetFunction.sum(WS.Columns(1))
  25. ' Mean is sum/row_count
  26. xbar = sum / row_count
  27. ' Loop through all rows, set range object, get squared Difference
  28. For i = 1 To row_count
  29. Set rng = WS.Cells(i, data_col_index) ' Sets range object
  30. 'spread = (rng.Value - xbar) ^ 2
  31. 'Debug.Print CDbl(spread)
  32. squared_diff = squared_diff + (rng.Value - xbar) ^ 2 ' (Calculates (measurement - mean) squared and adds to running total
  33. Next i
  34.  
  35. ' Calculate spread of sample
  36. variance = squared_diff / (sum - 1) ' variance = total of all squared differences (measurement - mean)^2 / n -1
  37. std_dev = Sqr(variance) ' standard deviation is variance squared
  38.  
  39. Debug.Print "SUM is " & sum
  40. Debug.Print "N - 1 is " & row_count - 1
  41. Debug.Print "XBAR is " & xbar
  42. Debug.Print "VAR is " & variance
  43. Debug.Print "STD_DEV is " & std_dev
  44.  
  45. WS.Cells(2, 3).Value = std_dev
  46.  
  47. End Sub
  48.  
  49. 7.436566035
  50. 7.273077821
  51. 7.421956493
  52. 7.191491523
  53. 7.41702391
  54. 7.248892198
  55. 7.289012484
  56. 7.296538223
  57. 7.326332635
Add Comment
Please, Sign In to add comment