Attribute VB_Name = "Modul1"
Option Explicit

Function FormatKomplex(NumToFormat As String, RealFormatCode As _
    String, ImagFormatCode As String)

    Dim PlusOrMinus As String
    Dim CharPosition As Integer
    Dim Found As Boolean
    
    For CharPosition = 1 To Len(RealFormatCode)
        If Mid(RealFormatCode, CharPosition, 1) = "," Then
            Mid(RealFormatCode, CharPosition, 1) = "."
            Found = True
        End If
        If Not Found And Mid(RealFormatCode, CharPosition, 1) = "." Then _
            Mid(RealFormatCode, CharPosition, 1) = ","
    Next
    For CharPosition = 1 To Len(ImagFormatCode)
        If Mid(ImagFormatCode, CharPosition, 1) = "," Then
            Mid(ImagFormatCode, CharPosition, 1) = "."
            Found = True
        End If
        If Not Found And Mid(ImagFormatCode, CharPosition, 1) = "." Then _
            Mid(ImagFormatCode, CharPosition, 1) = ","
    Next

    ' Is NumToFormat real?
    If Right(NumToFormat, 1) <> "i" Then
        ' NumToFormat is real.
        FormatKomplex = 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.
                FormatKomplex = 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.
                FormatKomplex = Format(Left(NumToFormat, _
                    CharPosition - 1), RealFormatCode) & "+" & _
                    Format(Mid(NumToFormat, CharPosition, _
                    Len(NumToFormat) - CharPosition), _
                    ImagFormatCode) & "i"
            End If
        Else
            ' NumToFormat is imaginary.
            FormatKomplex = Format(Left(NumToFormat, _
                Len(NumToFormat) - 1), ImagFormatCode) & "i"
        End If
    End If
End Function


