首页 > 解决方案 > Powershell excel粘贴值

问题描述

我有一个 excel 文件,里面有几张纸。我试图将所有这些组合成一张纸。我有执行此操作的代码,但我现在遇到的问题是现在工作表上有公式。因此,当它复制到新工作表时,它不会复制值,而是复制公式。我在网上阅读你可以做这个pastespecial,但我不能让它工作。有没有人有关于如何将一张纸复制到另一张纸的代码,但保留这些值。一个问题是工作表的行数不同,所以我不确定范围是多少。我已经尝试了很多事情,我只是想明白了。

这是使用 excel.application

对于问题,问题是我无法弄清楚.PasteSpecial。

这是现在将其复制到名为 combine 的工作表的代码。

$wb = $excel.Workbooks.Open($location)
$newSheetName = 'Combine'
$xlCellTypeLastCell = 11
$targetSheet = $wb.Sheets.Add()
$targetSheet.Name = $newSheetName
$includeHeader = $true
foreach ($sh in $wb.Sheets) {
        $statename = $sh.Name
        if($sh.name -eq "Available" -or $sh.name -eq "Eligible"){
        }else{
        $sh.autofiltermode = $false
        $sourceRange = $sh.UsedRange
        if ($sourceRange.Rows.Count -le 1) { continue }
        # if ($sourceRange.Rows.Count -le 1 -or $sh.Name -eq $newSheetName) {continue}
        $targetLastCell = $targetSheet.UsedRange.SpecialCells($xlCellTypeLastCell)
        if ($includeHeader) {
            [Void]$sourceRange.PasteSpecial($targetLastCell)
        }
        else {
            $columnOffset = - $targetLastCell.Column + 1
            $targetCell = $targetLastCell.Offset(1, $columnOffset)
            $newRowCount = $sourceRange.Rows.Count - 1
            [Void]$sourceRange.Offset(1, 0).Resize($newRowCount).Copy($targetCell)
        }
        $includeHeader = $false
}
}

这确实适用于标题,但此时我并不真正关心这些。我会说 UsedRange 也想念我。所以现在我只使用 .copy 并且从在线阅读中我需要使用 pasteSpecial。

标签: powershell

解决方案


推荐阅读