I try to set a range of different formulas, but it does not work via Delphi.
To illustrate this, I have some VBA test-code that I can execute directly in Excel:
Public Sub Test()
Range(Cells(1, 1), Cells(1, 1)).Formula = "=Complex(1, 1.2)"
Dim vFormula(1 To 2) As Variant
vFormula(1) = "=Complex(0, 0.1)"
vFormula(2) = "=Complex(1, 1.2)"
Range(Cells(2, 1), Cells(2, 2)).Formula = vFormula
End Sub
and it works as expected:
Notes:
A1
contains a single formulaA2
, B2
have been set with one call using a variant array of stringsComplex
is shown in German KOMPLEXE
in the screenshot - sweetNow I try to do the same via Delphi:
procedure TForm1.btnAddRangeFormulasClick(Sender: TObject);
var
I: Integer;
VarArr: Variant;
begin
FWorksheet.Range['A1', 'A1'].Formula := '=Complex(1, 1.2)';
VarArr := VarArrayCreate([0, 1], varOleStr);
VarArrayPut(VarArr, '=Complex(0, 0.1)', [0]);
VarArrayPut(VarArr, '=Complex(1, 1.2)', [1]);
FWorksheet.Range['A2', 'B2'].Formula := VarArr;
end;
But this does not work as expected:
Notes:
A1
works as expectedA2
, B2
has not been convertedAny ideas what I am doing wrong and how to fix this?
I am using:
Another try is to use the Locale dependant formula in Delphi:
procedure TForm1.btnAddRangeFormulasGerClick(Sender: TObject);
var
VarArr: Variant;
begin
FWorksheet.Range['A1', 'A1'].Formula := '=Komplexe(1, 1.2)';
VarArr := VarArrayCreate([0, 1], varOleStr);
VarArrayPut(VarArr, '=Komplexe(0, 0.1)', [0]);
VarArrayPut(VarArr, '=Komplexe(1, 1.2)', [1]);
FWorksheet.Range['A2', 'B2'].Formula := VarArr;
end;
this also does not work right away:
Notes:
#Name
FormulaLocal
instead of Formula
I must create a variant array of varVariant
(instead of varOleStr
) like this:
VarArrayCreate([0, 1], varVariant);
Then all my use-cases including the automatic formula translation work!
Thanks @Vityata
In VBA, .Formula
takes the original English formula and it transfers it to Excel. Then, based on the local Excel installation, it is "translated". Thus, =Complex()
becomes =Komplexe()
in German.
Obviously in Delphi, this works in a similar way. .Formula
translates correctly your English formula to German, thus A1
is ok. The VarArrayPut
probably takes Text
and not Formula
, thus it should be at the local language:
You can give it a try:
VarArrayPut(VarArr, '=Komplexe(0, 0.1)', [0]);
As a last resort, if you can find an English installation of Excel, your Delphi code should be working. To get some ideas about the Excel local formula's translation, this is how a standard =IF()
formula gets translated:
"=IF(B1=C1,""Equal"",""Not equal"")"
"=IF(RC[1]=RC[2],""Equal"",""Not equal"")"
"=WENN(B1=C1,""Equal"",""Not equal"")"
"=WENN(ZS(1)=ZS(2),""Equal"",""Not equal"")"
Source (disclaimer - my site)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With