【问题标题】:Incorrect formula after copying Excel worksheet from another worksheet through powershell通过powershell从另一个工作表复制Excel工作表后公式不正确
【发布时间】:2019-08-09 08:11:30
【问题描述】:

我正在复制另一个工作簿中的工作表,但 B9、B10、B11、B12 和 H13 中的公式引用了以前的工作簿,它们不应该。我还想提一下,我有点菜鸟。

我试过以下代码:

    $sh2_wb2.Cells.Item(9,2).Value = "=Suivi!C6"
    $sh2_wb2.Cells.Item(9,2).Formula = '=Suivi!C6'
    $sh2_wb2.Cells.Item(9,2).Formula = "=Suivi!C6"
   $path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
    "Adding to $path"
    $file2 = $path # destination's fullpath
    $wb1 = $excel.workbooks.open($file1, $null, $true) # open source, readonly
    $wb1.unprotect('****') # unprotect source
    $wb2 = $excel.workbooks.open($file2) # open target
    $sh2_wb2 = $wb2.sheets.item(2) # second sheet in destination workbook
    $sheetToCopy = $wb1.sheets.item(2) # source sheet to copy
    $sheetToCopy.copy($sh2_wb2) # copy source sheet to destination workbook
    $sh2_wb2.Cells.Item(9,2).Value = "=Suivi!C6"
    $sh2_wb2.Cells.Item(10,2).Value = '=1!C1'
    $sh2_wb2.Cells.Item(11,2).Value = '=1!C3'
    $sh2_wb2.Cells.Item(12,2).Value = '=1!C4'
    $sh2_wb2.Cells.Item(13,8).Value = '=1!C2'
    $wb2.protect('****')
    $wb1.close($false) # close source workbook w/o saving
    $wb2.close($true) # close destination with saving

我没有收到任何错误。表 2 中的单元格 B9 应显示 =Suivi!C6。

【问题讨论】:

  • 这段代码中的$excel 是什么?你在使用ImportExcel 模块吗?

标签: excel powershell


【解决方案1】:

当您将工作表从一个工作簿复制到另一个工作表时,您在复制方法中引用的工作表指定将复制的工作表添加到工作簿时应将其放置在何处。它将在指定工作表之前插入源工作表。

所以你得到$sh2_wb2 = $wb2.sheets.item(2),并将其用作目标。复制完成后$sh2_wb2 不再是Item(2),现在是Item(3)Item(2) 是您刚刚复制到工作簿中的新工作表。因此,当您更改值时,您的目标是错误的工作表。如果您查看目标工作簿中的第三张工作表,您会注意到 B9:B12 和 H13 设置为您打算在刚刚复制的工作表上更新的内容。

如何解决?复制后重新获取第二张工作表,这是最简单的方法。

$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
"Adding to $path"
$file2 = $path # destination's fullpath
$wb1 = $excel.workbooks.open($file1, $null, $true) # open source, readonly
$wb1.unprotect('****') # unprotect source
$wb2 = $excel.workbooks.open($file2) # open target
$sh2_wb2 = $wb2.sheets.item(2) # second sheet in destination workbook
$sheetToCopy = $wb1.sheets.item(2) # source sheet to copy
$sheetToCopy.copy($sh2_wb2) # copy source sheet to destination workbook
$sh2_wb2 = $wb2.sheets.item(2) # new second sheet in destination workbook
$sh2_wb2.Cells.Item(9,2).Value = "=Suivi!C6"
$sh2_wb2.Cells.Item(10,2).Value = '=1!C1'
$sh2_wb2.Cells.Item(11,2).Value = '=1!C3'
$sh2_wb2.Cells.Item(12,2).Value = '=1!C4'
$sh2_wb2.Cells.Item(13,8).Value = '=1!C2'
$wb2.protect('****')
$wb1.close($false) # close source workbook w/o saving
$wb2.close($true) # close destination with saving

【讨论】:

  • 我必须在您的行之后添加 $sh2_wb2.unprotect('****') 才能取消保护工作表。现在一切正常!谢谢!
猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多