Excel & PowerShell - VLOOKUP 的 PasteSpecial 失败

Excel & PowerShell - PasteSpecial Failure With VLOOKUPs

我有一个 VLOOKUP 被插入到我的传播sheet 的 F 列中,如下所示:

$vLookup = "=VLOOKUP($refCol,'$xlsLocsDIR[locs.xlsx]Device'!`$B`:`$C$rowsDvcs,2,FALSE)"
$sheetSave.Cells.Item(2,6).Formula = $vLookup

明确地说,在 Excel 中正确保存如下:

=VLOOKUP(E2,'[locs.xlsx]Device'!$B:$C24549,2,FALSE)

(参考文件中有 ~25k 行,但在我有 VLOOKUP 的文件中有 超过 200k。)

由于我在其中执行 VLOOKUP 的文件的大小,并且客户可能使用 32 位 OS 或 Excel,我必须 Copy/Paste 一次不超过 30000 行,以填充所有 200k 行,如下所示:

#32-bit OS/Excel app compatibility
#Excel/32-bit OS/memory errors occur if doing more than 30k cells
#instead, we do 20k, save, 20k, save, etc

for ($i=2; $i -le $rowsTrans; ($i+30000))
{
    #set the stop point, not to exceed total usedrows
    if (($i + 30000) -gt $totalRows)
        {$j = $totalRows}
    else 
        {$j = ($i+30000)}

    #copy the data
    $copyCell = (("F" + $i))
    $copyRange = $sheetTrans.Range($copyCell)
    $copyRange.Copy() | Out-Null

    $sheetSave.Activate()
    $pasteRange = $sheetTrans.Range(("F"+$i+":F"+$j)).Select()
    $sheetSave.PasteSpecial(7)
    $fileWorking.Save()
}

我只想将单元格 F2 中的 VLOOKUP 公式复制到 F 列接下来的 20k 行中,然后保存文件并再次迭代,直到填充整个文件。

当我执行上述操作时,我尝试了除此示例之外的其他方法,我总是收到 MethodInvocation Error,除非我明确地使 file/sheet 可见,像这样,在上面的循环之前:

$xlsObject.Visible = $true

我对 Copy() / PasteSpecial() 函数调用有什么误解?为什么 sheet 必须可见?

注意我已尝试将上述代码匿名化并限制了解问题所需的内容。代码功能,我只是不想在任何时候要求 Excel 实例出现在视图中。我希望脚本 运行 对最终用户不可见。

我收到的 MethodInvocation 错误通常如下所示:

Exception calling "PasteSpecial" with "1" argument(s): "PasteSpecial method of Worksheet class failed" At line:1 char:25 + $sheetTrans.PasteSpecial <<<< (9) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation

我可以通过做一些直接引用来解决这个问题,改变我分配范围的方式,然后调用 PasteSpecial,就像这样:

$pasteRange = $sheetTrans.Range(("F"+$i+":F"+$j))
$pasteRange.PasteSpecial($xlPasteValues) | Out-Null

像这样的声明:

Add-Type -ASSEMBLY "Microsoft.Office.Interop.Excel" | out-null
$global:xlPasteFormulas = -4123
$global:xlPasteValues = -4163