excel - 如何使用 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 模块中的整数。我错过了什么?
解决方案
每当我遇到这种事情时,我都会使用“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()
推荐阅读
- ruby-on-rails - 在使用 RSpec 和 Factory-bot-rails 对控制器进行测试时,我得到“KeyError: Factory not registered: "user"'
- angular - 如何使用 `ng build --watch=true` 将所有 JS/CSS 内联到 html 中
- javascript - Express/Node.js .. 我阻塞了事件循环吗?
- powershell - 将具有多个工作表的多个 Excel 工作簿转换为 CSV:如何提取由公式构造的 url?
- javascript - 另一个承诺中的承诺
- php - 如何给页面一个特殊的 url 以在外部打开
- python - 了解贝叶斯过滤在 SciKit 中的工作原理并提高准确性
- php - 我如何制作一个表格来更新我的表格并在我的 TeamStats 页面上显示为一行?
- python - Python - 为什么我的数据没有被 sqlite3 中的这个循环正确添加?
- recurrent-neural-network - 循环神经网络预测遵循测试集的形状,但向下移动