Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Powershell减去Excel单元格_Excel_Powershell - Fatal编程技术网

如何使用Powershell减去Excel单元格

如何使用Powershell减去Excel单元格,excel,powershell,Excel,Powershell,我试图在现有的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

我试图在现有的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

我已经尝试将所有变量转换为int,但仍然会产生相同的错误。我甚至在用于创建此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()
# Instantiate Excel instance
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visible 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')

# Results

<#
Application                      : Microsoft.Office.Interop.Excel.ApplicationClass
Creator                          : 1480803660
Parent                           : Microsoft.Office.Interop.Excel.ApplicationClass
...
#>

# Assign a formula to the target variable
$strFormula =  "=((A1:C4/10000)-1)"

# Assign the formula to the target variable
$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula

<#
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
At line:1 char:1
+ $excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormul ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
#>

$Error | Format-List -Force

<#
Exception             : System.Management.Automation.RuntimeException: The variable '$command' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, 
                        VariableExpressionAst varAst)
                           at Prompt(Closure , FunctionContext )
TargetObject          : command
CategoryInfo          : InvalidOperation: (command:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at Prompt, C:\Users\Daniel\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1: line 55
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails      : 

...
#>

每当我遇到这种情况时,我都会打开“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()
# Instantiate Excel instance
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visible 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')

# Results

<#
Application                      : Microsoft.Office.Interop.Excel.ApplicationClass
Creator                          : 1480803660
Parent                           : Microsoft.Office.Interop.Excel.ApplicationClass
...
#>

# Assign a formula to the target variable
$strFormula =  "=((A1:C4/10000)-1)"

# Assign the formula to the target variable
$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula

<#
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
At line:1 char:1
+ $excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormul ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
#>

$Error | Format-List -Force

<#
Exception             : System.Management.Automation.RuntimeException: The variable '$command' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, 
                        VariableExpressionAst varAst)
                           at Prompt(Closure , FunctionContext )
TargetObject          : command
CategoryInfo          : InvalidOperation: (command:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at Prompt, C:\Users\Daniel\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1: line 55
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails      : 

...
#>

我现在意识到我引用的单元格值不正确。正确的方法是:

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

我现在意识到我引用的单元格值不正确。正确的方法是:

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

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

然而,在你发布的代码中,没有任何一点是你让XLS可见,让你按照它行事。由于它不可见,因此无法对其执行UI操作

第二,这

$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula
。。。这是你的问题开始的地方。如果您一步一步地完成这一步,您将立即看到前面提到的操作将失败

例如:

# 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()
# Instantiate Excel instance
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visible 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')

# Results

<#
Application                      : Microsoft.Office.Interop.Excel.ApplicationClass
Creator                          : 1480803660
Parent                           : Microsoft.Office.Interop.Excel.ApplicationClass
...
#>

# Assign a formula to the target variable
$strFormula =  "=((A1:C4/10000)-1)"

# Assign the formula to the target variable
$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula

<#
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
At line:1 char:1
+ $excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormul ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
#>

$Error | Format-List -Force

<#
Exception             : System.Management.Automation.RuntimeException: The variable '$command' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, 
                        VariableExpressionAst varAst)
                           at Prompt(Closure , FunctionContext )
TargetObject          : command
CategoryInfo          : InvalidOperation: (command:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at Prompt, C:\Users\Daniel\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1: line 55
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails      : 

...
#>
#实例化Excel实例
$excel\u test=新对象-ComObject excel.Application
#使实例可见以使用它
$excel\u test.visible=$true
#捕捉警报
$excel\u test.DisplayAlerts=$true
#添加到文件源中
$excel\u test.Workbooks.Add('D:\Temp\test.xlsx')
#结果
#为目标变量指定一个公式
$strFormula=“=(A1:C4/10000)-1)”
#将公式指定给目标变量
$excel\u test.Worksheets.Item(2).Cells.Item(2,2).Formula()=$strFormula
$Error |格式列表-强制

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

然而,在你发布的代码中,没有任何一点是你让XLS可见,让你按照它行事。由于它不可见,因此无法对其执行UI操作

第二,这

$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula
。。。这是你的问题开始的地方。如果您一步一步地完成这一步,您将立即看到前面提到的操作将失败

例如:

# 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()
# Instantiate Excel instance
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visible 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')

# Results

<#
Application                      : Microsoft.Office.Interop.Excel.ApplicationClass
Creator                          : 1480803660
Parent                           : Microsoft.Office.Interop.Excel.ApplicationClass
...
#>

# Assign a formula to the target variable
$strFormula =  "=((A1:C4/10000)-1)"

# Assign the formula to the target variable
$excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormula

<#
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
At line:1 char:1
+ $excel_test.Worksheets.Item(2).Cells.Item(2,2).Formula() = $strFormul ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
#>

$Error | Format-List -Force

<#
Exception             : System.Management.Automation.RuntimeException: The variable '$command' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, 
                        VariableExpressionAst varAst)
                           at Prompt(Closure , FunctionContext )
TargetObject          : command
CategoryInfo          : InvalidOperation: (command:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at Prompt, C:\Users\Daniel\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1: line 55
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails      : 

...
#>
#实例化Excel实例
$excel\u test=新对象-ComObject excel.Application
#使实例可见以使用它
$excel\u test.visible=$true
#捕捉警报
$excel\u test.DisplayAlerts=$true
#添加到文件源中
$excel\u test.Workbooks.Add('D:\Temp\test.xlsx')
#结果
#为目标变量指定一个公式
$strFormula=“=(A1:C4/10000)-1)”
#将公式指定给目标变量
$excel\u test.Worksheets.Item(2).Cells.Item(2,2).Formula()=$strFormula
$Error |格式列表-强制

实际上,您可能希望使用value属性vs text来确保获得数字,因此无需强制转换。我已经尝试过了,但不幸的是,它仍然不起作用,但不知何故使用了.text works。有趣的是,作为示例,使用value属性,我按预期添加了post works,但是如果您所做的工作正常,那么,我明白了。实际上,你可能想使用value属性vs text来确保你得到的是数字,因此不需要强制转换。我已经尝试过了,但不幸的是,它仍然不起作用,但不知怎的,使用了.text worksinterest,作为示例,使用value属性,我按预期添加了post works,但是如果你所做的工作正常,那么,我明白了。