I want to write a custom function that works out the overall A-Weighted dB level of a linear spectrum of octave band frequencies (eg. 31.5 Hz-16kHz). The function would need to have an input of two ranges (e.g. A1-10 with octave mid-band frequencies, and B1-10 with spectral data: L1-L10) and add an attenuation factor to each level in each octave band before summing them logarithmically (10*log10(10^(L1/10)+10^(L2/10)etc.)). I've managed to write one that will do the backend, which is below:
Public Function DBSUM(rng As Range) As Double
Dim wf As WorksheetFunction, r As Range, Z As Double
Set wf = Application.WorksheetFunction
For Each r In rng
Z = Z + 10 ^ (r.Value / 10)
Next r
DBSUM = 10 * wf.Log10(Z)
End Function
I've tried to use the switch function to adapt the first formula, but I know I'm way off. I feel like I'll have to write two seperate loops and somehow link them, but I have no idea how to do that. Below is what I have so far, so could someone tell me how wrong I am?
Public Function DBA(rng1 As Range, rng2 As Range) As Double
Dim wf As WorksheetFunction, r1 As Range, r2 As Range, Z1 As Double, Z2 As Double
Set wf = Application.WorksheetFunction
For Each r1 In rng1
Z1 = Z1 + Switch(r2.Value = 31.5, r1.Value - 39.4, r2.Value = 63, r1.Value - 26.2, r2.Value = 125, r1.Value - 16.1, r2.Value = 250, r1.Value - 8.6, r2.Value = 500, r1.Value - 3.2, r2.Value = 1000, r1.Value, r2.Value = 2000, r1.Value + 1.2, r2.Value = 4000, r1.Value + 1, r2.Value = 8000, r1.Value - 1.1, r2.Value = 16000, r1.Value - 6.6)
Next r1
For Each r2 In rng2
Z2 = Z2 + 10 ^ (Z1 / 10)
Next r2
DBA = 10 * wf.Log10(Z2)
End Function