简体   繁体   English

如何在powershell中选择Excel范围

[英]How to select Excel range in powershell

I have the following code in a function:我在一个函数中有以下代码:

function Excel2PPT{


param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)
    $Excel = New-Object -ComObject Excel.Application
    $workbook = $Excel.workbooks.open($xslx)
    $Excel.Visible= $true
    $worksheet = $workbook.worksheets.Item($targetsheet)

$range = $worksheet.Range($targetrange)
$range.select()
$range.copy()

I am using it in another function which passes to it "A1:O12" as $targetrange我在另一个函数中使用它作为 $targetrange 传递给它“A1:O12”

This worked in previous testing but now yields an error and unexpected behavior.这在之前的测试中有效,但现在会产生错误和意外行为。

I reference it as:我将其引用为:

Excel2PPT $IncomingABCExcel 1 'A1-O12' $testPPT2 $Targetslide $testPPT3

The error is:错误是:

Exception from HRESULT: 0x800A03EC
At C:\...\Excel2PPT.ps1:16 char:1
+ $range = $worksheet.Range($targetrange)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:17 char:1
+ $range.select()
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:18 char:1
+ $range.copy()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

What can I do to fix it?我能做些什么来修复它? It should be copying and pasting $targetrange to the intended PPT slide but it appears to be copying and pasting "$IncomingABCExcel" (not the variable, the variable name) onto the slide.它应该将 $targetrange 复制并粘贴到预期的 PPT 幻灯片,但它似乎是将“$IncomingABCExcel”(不是变量,变量名称)复制并粘贴到幻灯片上。

The issue you are having is that you are using 'A1-012' As the range.您遇到的问题是您使用的是“A1-012”作为范围。 This should be 'A1:012':这应该是“A1:012”:

function Excel2PPT {
    param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)

    $Excel = New-Object -ComObject Excel.Application
    $workbook = $Excel.workbooks.open($xslx)
    $Excel.Visible= $true
    $worksheet = $workbook.worksheets.Item($targetsheet)
    $range = $worksheet.Range($targetrange)
    $range.select()
    $range.copy()
}

Excel2PPT $IncomingABCExcel 1 'A1:O12' $testPPT2 $Targetslide $testPPT3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM