Article ID: 151338
Article Last Modified on 8/17/2005
=FormatComplex(A1,"0.00","0.0000")would display the complex number in cell A1 with two decimal places for the real component and four decimal places for the imaginary component.
=FormatComplex(A1,"0.00;-0.00;0","0.0000;-0.0000;0")would have the same result as the earlier example, but with zero components displaying as "0" rather than including extra zeroes to the right of the decimal point. If you use a multisection format, the formats for negative numbers must begin with a "-" (minus sign) as in the example.
Option Explicit
Function FormatComplex(NumToFormat As String, RealFormatCode As _
String, ImagFormatCode As String)
Dim PlusOrMinus As String
Dim CharPosition As Integer
' Is NumToFormat real?
If Right(NumToFormat, 1) <> "i" Then
' NumToFormat is real.
FormatComplex = Format(NumToFormat, RealFormatCode)
Else
' NumToFormat is either imaginary or complex.
' Search NumToFormat from right until + or - or left end is
' reached.
PlusOrMinus = "not found"
For CharPosition = Len(NumToFormat) - 1 To 1 Step -1
PlusOrMinus = Mid(NumToFormat, CharPosition, 1)
If PlusOrMinus = "+" Or PlusOrMinus = "-" Then Exit For
Next
' Is NumToFormat complex or imaginary?
If (PlusOrMinus = "+" Or PlusOrMinus = "-") And _
CharPosition <> 1 Then
' NumToFormat is complex.
' Is imaginary component negative?
If Mid(NumToFormat, CharPosition, _
Len(NumToFormat) - CharPosition) < 0 Then
' Imaginary component is negative, so "-" does not need
' to be added.
FormatComplex = Format(Left(NumToFormat, _
CharPosition - 1), RealFormatCode) & _
Format(Mid(NumToFormat, CharPosition, _
Len(NumToFormat) - CharPosition), _
ImagFormatCode) & "i"
Else
' Imaginary component is not negative, so "+" needs to
' be added.
FormatComplex = Format(Left(NumToFormat, _
CharPosition - 1), RealFormatCode) & "+" & _
Format(Mid(NumToFormat, CharPosition, _
Len(NumToFormat) - CharPosition), _
ImagFormatCode) & "i"
End If
Else
' NumToFormat is imaginary.
FormatComplex = Format(Left(NumToFormat, _
Len(NumToFormat) - 1), ImagFormatCode) & "i"
End If
End If
End Function
226118 OFF2000: Programming Resources for Visual Basic for Applications
Additional query words: 5.00a 5.00c 8.00 XL98 XL97 XL7 XL5 XL
Keywords: kbhowto kbprogramming kbdtacode KB151338