Search code examples
excelvbacomplex-numbers

How to square an imaginary number in VBA?


I'm working with imaginary numbers in VBA and part of the math I'm trying to implement involved squaring imaginary numbers. Now I tried to square a complex number in the immediate window but got a "type mismatch run-time 13" error. Here is the code below.

? WorksheetFunction.Complex(k1, -1*rho*sigma*phi)
? (WorksheetFunction.Complex(k1, -1*rho*sigma*phi))^2 

The second line is where I'm getting an error and I'm not sure how to square this complex number in VBA. Tried to look online as well but was unable to find anything useful.


Solution

  • You can use ImProduct or ImPower worksheet functions.

    Sub WorkingWithComplexNumbers()
      Dim vNum As Variant
      Dim wf As WorksheetFunction
      Set wf = WorksheetFunction
      
      vNum = wf.Complex(2, 3)
      
      Debug.Print wf.ImProduct(vNum, vNum)
      Debug.Print wf.ImPower(vNum, 2)
    End Sub
    

    If you type WorksheetFunction.im you will get a list of all functions you can use on a complex number.