Forum Discussion
Excel VBA
I've encoutered a weird value using excel VBA, attached below is the code. I found that whenever i tried to print AMBA, it gives me -3.014722032 whereas it should be 0.1268. the latter value can also be obtained if I change pi into 3.14 in AMBA = Pi - AAMB - AMAB .... It's weird that if I change it back into pi, -3.014 is instead obtained. why is this?
Function TransportCalc(array1 As Range, xM, yM, zM, z$)
'--input Base Case data
xA = WorksheetFunction.Index(array1, 1, 1)
yA = WorksheetFunction.Index(array1, 1, 4)
xB = WorksheetFunction.Index(array1, 2, 1)
yB = WorksheetFunction.Index(array1, 2, 4)
xc = WorksheetFunction.Index(array1, 3, 1)
yc = WorksheetFunction.Index(array1, 3, 4)
xD = WorksheetFunction.Index(array1, 4, 1)
yD = WorksheetFunction.Index(array1, 4, 4)
'--Distance Between Hydraulic Points
LAB = ((xA - xB) ^ 2 + (yA - yB) ^ 2) ^ (1 / 2)
LBC = ((xB - xc) ^ 2 + (yB - yc) ^ 2) ^ (1 / 2)
LCD = ((xc - xD) ^ 2 + (yc - yD) ^ 2) ^ (1 / 2)
LDA = ((xD - xA) ^ 2 + (yD - yA) ^ 2) ^ (1 / 2)
'--Distance Between Hydraulic Points and COG M
LMA = ((xA - xM) ^ 2 + (yA - yM) ^ 2) ^ (1 / 2)
LMB = ((xB - xM) ^ 2 + (yB - yM) ^ 2) ^ (1 / 2)
LMC = ((xc - xM) ^ 2 + (yc - yM) ^ 2) ^ (1 / 2)
LMD = ((xD - xM) ^ 2 + (yD - yM) ^ 2) ^ (1 / 2)
'--Angle calc, ccw naming
AMAB = WorksheetFunction.Acos((LMA ^ 2 + LAB ^ 2 - LMB ^ 2) / (2 * LMA * LAB))
AMBC = WorksheetFunction.Acos((LMB ^ 2 + LBC ^ 2 - LMC ^ 2) / (2 * LMB * LBC))
AMCD = WorksheetFunction.Acos((LMC ^ 2 + LCD ^ 2 - LMD ^ 2) / (2 * LMC * LCD))
AMDA = WorksheetFunction.Acos((LMD ^ 2 + LDA ^ 2 - LMA ^ 2) / (2 * LMD * LDA))
'--Tipping Length
T_AB = LMA * Sin(AMAB)
T_BC = LMB * Sin(AMBC)
T_CD = LMC * Sin(AMCD)
T_DA = LMD * Sin(AMDA)
'--Initiate Axle Load Calc
AP = Cos(AMA) * LMA
BQ = Cos(AMB) * LMB
CR = Cos(AMC) * LMC
DS = Cos(AMD) * LMD
'--AB shall be the line datum to draw the first perpendicular line from COG M
AAMB = WorksheetFunction.Acos((LMA ^ 2 + LMB ^ 2 - LAB ^ 2) / (2 * LMA * LMB))
AMBA = Pi - AAMB - AMAB
APMB = Pi - AMBA - Pi / 2
'--Tipping Length
Select Case (z$)
Case "TAB": TransportCalc = T_AB
Case "TBC": TransportCalc = T_BC
Case "TCD": TransportCalc = T_CD
Case "TDA": TransportCalc = T_DA
Case "AAMB": TransportCalc = AAMB
Case "AMAB": TransportCalc = AMAB
Case "AMBA": TransportCalc = AMBA
End Select
End Function
'---
1 Reply
Seems this is an unexpected value for AMBA in your VBA code likely stems from precision issues with the constant Pi and the WorksheetFunction.Acos calculation