I'm writing a VBA function which I need in my Excel spreadsheet, this is the code I wrote:
Function costo(x As Variant, d1 As Double, p1 As Double)
Dim d As Variant
d = Array(Array(129, 90), Array(129, 98), Array(142, 81), Array(133, 98), _
Array(139, 102), Array(156, 144), Array(125, 127), Array(137, 222), _
Array(213, 241), Array(145, 229), Array(206, 118), Array(152, 167))
Dim c As Double
c = 0
Dim i As Long
For i = 1 To 12
c = c + 50 * x(i) * distanza(d1, p1, d(i)(0), d(i)(1))
Next i
costo = c
End Function
Function distanza(ByVal d1 As Double, ByVal p1 As Double, ByVal d2 As Double, ByVal p2 As Double) As Double
Dim r As Double
r = 6371
distanza = 2 * r * WorksheetFunction.Asin(Sqr(WorksheetFunction.Power(Sin((d1 - d2) / 2), 2) + _
Cos(d1) * Cos(d2) * WorksheetFunction.Power(Sin((p1 - p2) / 2), 2)))
End Function
x are 12 cells of my spreadsheet, while d1 and p1 are two cell.
When I run the code in debug, the variable costo have the correct value, but in my spreedsheet I get #VALUE!.
Any suggestion?
Debug.? lbound(d, 1), ubound(d, 1)costofrom a Sub, then you can debug it.As valuedeclaration.costo. Most likely pointed by @GSerg. In this case Excel not informs about error. Cell value become #VALUE!. Check errors withon errorclause.Xis defined maybe it is referenced byx(i+1)or remains byx(i)