首页 > 解决方案 > 如何使用 Powershell 减去 Excel 单元格

问题描述

我正在尝试在其中包含数字的现有 Excel 工作表上执行算术运算。我的代码:

$Excel = New-Object -ComObject Excel.Application
$ExcelWorkBook = $Excel.Workbooks.Open($temp)
$ExcelWorkSheet = $Excel.WorkSheets.item(1)
$ExcelWorkSheet.activate()



$Prehit = $ExcelWorkSheet.Cells.Item(2,1)
$Hit1 = $ExcelWorkSheet.Cells.Item(2,2)
$Hit2 = $ExcelWorkSheet.Cells.Item(2,3)
$Hit3 = $ExcelWorkSheet.Cells.Item(2,4)

$Remain = 0


If ($hit -eq 1) {
  $Remain = $Prehit - $Hit1

  }



If ($hit -eq 2) {
  $Remain = $Prehit - $Hit1- $Hit2

  }

产生以下错误:

Method invocation failed because [System.__ComObject] does not contain a method named 'op_Subtraction'.
At C:\path_to_ps1_file.ps1:40 char:3
+   $Remain = $Prehit - $Hit1- $Hit2
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Subtraction:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

我尝试将所有变量转换为整数,但会产生相同的错误。我什至将数字转换为用于创建此 excel 文件的 powershell 模块中的整数。我错过了什么?

标签: excelpowershell

解决方案


每当我遇到这种事情时,我都会使用“Excel Marco Recorder”并查看它生成的 VBA 代码,然后将其转换为 PowerShell 以供以后的自动化用例使用。

然而,在您发布的代码中,您并没有让 XLS 可见以供您对其采取行动。

例如:

# Instantiate Excel instnace
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visiable to work with it
$excel_test.visible = $true

# Catch alerts
$excel_test.DisplayAlerts = $true

# Add in the file source
$excel_test.Workbooks.Add('D:\Temp\Test.xlsx')

# Choose a sheet in the workbook
$Sheet = $excel_test.Worksheets.Item(1)

# Assign a formula to the target variable
$strFormula =  '=(SUM(A1:C3)/3) - 1'

# Assign the formula to the target variable
$Sheet.Cells.Item(4,4) = $strFormula
$SourcecellCell = ($Sheet.Cells.Item(4,4)).Value2
$NewCell = 3
$sheet.Cells.Item(5,5) = $SourcecellCell - $NewCell

# Exit the XLS without saving
$excel_test.Quit()

推荐阅读