Powershell:如何在不迭代所有行和列的情况下检索公式?

时间:2012-03-12 06:34:06

标签: excel powershell excel-2003

以下是我的示例代码:

$wb = $excel.ActiveWorkbook

ForEach ($ws in $wb.Worksheets) {
    "Working on {0}" -f $ws.Name
    forEach ($row in $ws.Rows) {
        forEach($cell in $row.Cells) {
            if ($cell.HasFormula) {
                $formula = $cell.Formula
                if ( ($formula -match "foobar") {                
                    "{0} R{1}C{2}:{3}" -f $ws.Name, $row.Row, $cell.Column, $formula
                }
            }
        }
    }
}

由于电子表格太大,性能不佳。我想

1)我可以在一个函数调用中检索所有公式吗? excel是否支持它?

2)如果将公式分配给单元格数组,我该如何提取公式?

1 个答案:

答案 0 :(得分:2)

也许这个link可以给你一些提示来获取表格中的公式列表。

$excel = New-Object -com Excel.Application
$excel.Workbooks.Open( "C:\cartel1.xls" )
$sheet = $excel.Sheets.item(1) # select the sheet to looking for formulas
$cellsWithFormula = $sheet.Cells.SpecialCells( -4123 , 23) # (XlCellType constant, XlSpecialCellsValue constant) - Return a Range of cell with formula
$cellsWithFormula |  select row, column, formula, formulaArray | ft -autosize # get a list of cell and formula and formulaArray

注意:type xlCell Constants