如何使用Win32 :: OLE设置Excel公式?

时间:2009-11-04 16:28:57

标签: perl excel excel-formula win32ole

任何人都可以告诉我,为什么...->{FormulaR1C1} = '=SUMME( "R[-3]C:R[-1]C" )';不起作用。在应该出现结果的Cell中,我得到“#Wert!” (也许是英文中的“价值”)。通过WENN(IF)-formula,我得到了我的期望。

#!C:\Perl\bin\perl.exe
use warnings;
use strict;
use Win32::OLE qw;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;
my $xl = Win32::OLE::Const -> Load( 'Microsoft Excel' );
my $excelfile = 'win32_ole_excel.xls';
my $excel = Win32::OLE -> GetActiveObject( 'Excel.Application' ) || Win32::OLE -> new( 'Excel.Application', 'Quit' ) or die $!;

my $workbook = $excel -> Workbooks -> Add();
my $sheet = $workbook -> Worksheets( 1 );
$sheet -> Activate;


$sheet->Range( 'A3' )->{Value} = 10;
$sheet->Range( 'B3' )->{FormulaR1C1} = '=WENN( "RC[-1]" > 5; "OK"; "Not OK")'; # IF(,,); workes fine


$sheet->Range( 'G1' )->{Value} = 3;
$sheet->Range( 'G2' )->{Value} = 7;
$sheet->Range( 'G3' )->{Value} = 6;
$sheet->Range( 'G4' )->{FormulaR1C1} = '=SUMME( "R[-3]C:R[-1]C" )'; # SUM(); doesn't work


$workbook -> SaveAs( { Filename => $excelfile, FileFormat => xlWorkbookNormal } );

2 个答案:

答案 0 :(得分:2)

SUM范围内不需要引号。它应该是明确的:

=SUMME(R[-3]C:R[-1]C)

附加要点 - 您的IF / WENN公式不正确。它试图将字符串“RC [-1]”与数字5进行比较,然后得出YES!弦乐更大。它没有做你认为它正在做的事情......你也应该在这里引用参考文献。

编辑:这是我的代码版本,运行时没有任何错误。更改被评论。不得不对英文版的Excel应用一些更改。赶上 ActivePerl 5.10.1 Build 1006

#!C:\Perl\bin\perl.exe
use warnings;
use strict;
# CHANGE - empty qw caused compilation error
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;
my $xl = Win32::OLE::Const -> Load( 'Microsoft Excel' );
# CHANGE - set path
my $excelfile = 'C:\win32_ole_excel.xls';
my $excel = Win32::OLE -> GetActiveObject( 'Excel.Application' ) || Win32::OLE -> new( 'Excel.Application', 'Quit' ) or die $!;

my $workbook = $excel -> Workbooks -> Add();
my $sheet = $workbook -> Worksheets( 1 );
$sheet -> Activate;

$sheet->Range( 'A3' )->{Value} = 10;
# CHANGE - Use IF, use commas, took quotes out around range
$sheet->Range( 'B3' )->{FormulaR1C1} = '=IF( RC[-1] > 5, OK, Not OK)'; # IF(,,); workes fine

$sheet->Range( 'G1' )->{Value} = 3;
$sheet->Range( 'G2' )->{Value} = 7;
$sheet->Range( 'G3' )->{Value} = 6;
# CHANGE - Use SUM, took quotes out around range
$sheet->Range( 'G4' )->{FormulaR1C1} = '=SUM(R[-3]C:R[-1]C)'; # SUM(); doesn't work

$workbook -> SaveAs( { Filename => $excelfile, FileFormat => xlWorkbookNormal } );

答案 1 :(得分:1)

perl-community.de的帮助下,我现在有了一个解决方案: 我必须设置

$excel->{ReferenceStyle} = $xl->{xlR1C1};

并使用Z1S1代替R1C1

=SUMME(Z(-2)S:Z(-1)S)

但看起来在德语版本中,我必须在A1Z1S1R1C1)符号之间进行选择。