There is a macro that performs simple calculations:
Attribute VB_Name = "Calculate"
Function Calculate(ByVal num1 As Double, ByVal num2 As Double, ByVal operator As String) As Double
Dim result As Double
Select Case operator
Case "sum"
result = num1 + num2
Case "sub"
result = num1 - num2
Case "mul"
result = num1 * num2
Case "div"
If num2 <> 0 Then
result = num1 / num2
Else
MsgBox "You can't divide by zero!"
Exit Function
End If
Case Else
MsgBox "Wrong operator!"
Exit Function
End Select
Return result
End Function
This is my test (does not pass because the result does not return):
[Test]
[TestCase(1, 2, "sum", 3)]
[TestCase(7, 3, "mul", 21)]
public void Execute_RunCalculateMacro_ShouldReturnTrueValue(double num1, double num2,
string operation, double expected)
{
var result = (double)RunExternalMacro(openedWord, macroPath, funcName, num1, num2, operation);
Assert.AreEqual(expected, result);
}
Here is the method that runs this macro:
public object RunExternalMacro(Application openedWord, string macroPath, string funcName,
double num1, double num2, string operation)
{
openedWord.ActiveDocument.VBProject.VBComponents.Import(macroPath);
var result = app.Run(funcName, num1, num2, operation);
var lastVBComponent = openedWord.ActiveDocument.VBProject.VBComponents.LastOrDefault();
if (lastVBComponent != null)
{
openedWord.ActiveDocument.VBProject.VBComponents.Remove(lastVBComponent);
}
return result;
}
The problem is that the result of the macro is only displayed in a new Word document window (MsgBox). And the result variable always returns null.
Is there any way I can get the result of the macro in the result variable? What am I doing wrong?