VBA Code


Using a Custom Worksheet Function


Public Function QUADRATIC(sngValueA As Single, _ 
                          sngValueB As Single, _
                          sngValueC As Single) As Variant

Dim vReturnArray() As String
Dim sngDeterminant As Single
Dim sngreal As Single
Dim sngimaginary As Single
  
   Call Application.Volatile(True)
   ReDim vReturnArray(2)
   
   If sngValueA = 0 Then Call MsgBox("The value of A cannot be 0")
   If sngValueA = 0 Then Exit Function

   sngDeterminant = (sngValueB * sngValueB) - (4 * sngValueA * sngValueC)
   
   Select Case sngDeterminant
   
      Case Is < 0
         vReturnArray(0) = "Two Complex"
   
         sngreal = -sngValueB / (2 * sngValueA)
         sngimaginary = VBA.Sqr(-sngDeterminant) / (2 * sngValueA)
                  
         If sngreal <> 0 Then vReturnArray(1) = VBA.Round(sngreal, 2)
         If sngreal <> 0 Then vReturnArray(2) = VBA.Round(sngreal, 2)
         
         If sngreal <> 0 And sngimaginary <> 0 Then
            vReturnArray(1) = vReturnArray(1) & "+"
            vReturnArray(2) = vReturnArray(2) & "-"
         End If
         If sngimaginary <> 0 Then
            vReturnArray(1) = vReturnArray(1) & VBA.Round(sngimaginary, 2) & "i"
            vReturnArray(2) = vReturnArray(2) & -VBA.Round(sngimaginary, 2) & "i"
         End If
            
      Case Is = 0
         vReturnArray(0) = "One Real"
         vReturnArray(1) = -sngValueB / (2 * sngValueA)
         vReturnArray(1) = VBA.Round(vReturnArray(1), 3)
         
         vReturnArray(2) = "-"
   
      Case Is > 0
         vReturnArray(0) = "Two Real"
         vReturnArray(1) = (-sngValueB + VBA.Sqr(sngDeterminant)) / (2 * sngValueA)
         vReturnArray(1) = VBA.Round(vReturnArray(1), 3)
         
         vReturnArray(2) = (-sngValueB - VBA.Sqr(sngDeterminant)) / (2 * sngValueA)
         vReturnArray(2) = VBA.Round(vReturnArray(2), 3)
         
   End Select

   QUADRATIC = vReturnArray
End Function




© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext