简体   繁体   English

PowerShell - 找到起始行后从 Excel 中删除一系列行

[英]PowerShell - Delete a Range of Rows from Excel After Locating Starting Row

I have a PowerShell script that searches an Excel file for a specific value ("#N/A", from a failed VLOOKUP) that needs to have all of the rows AFTER and including that row deleted quickly.我有一个 PowerShell 脚本,用于在 Excel 文件中搜索特定值(“#N/A”,来自失败的 VLOOKUP),该值需要快速删除 AFTER 和包括该行的所有行。

What I have done so far:到目前为止我做了什么:

$sheetRange = $sheetData.UsedRange
$colRange = $sheetData.Range("F1")
[void] $sheetRange.Sort($colRange)
$fileWorking.Save()

$strFinder = "#N/A"
$rngSearch = $sheetData.Range("F1").EntireColumn
$txtFound = $rngSearch.Find($strFinder)
$RowFound = ($txtFound.Row)
for (($i = $RowFound); ($i -le $rowsTrans); $i++)
{
  $currRow = $sheetData.Cells.Item($i).EntireRow
  [void]$currRow.Delete()
}
$fileWorking.Save()

The problem is, there are over 200k rows, and I need to delete the entire range instead of one row at a time.问题是,有超过 20 万行,我需要删除整个范围而不是一次删除一行。 While I have muddled around with the syntax some, I can't quite figure out the proper syntax or methods that accomplish this.虽然我对语法有些困惑,但我无法弄清楚实现这一点的正确语法或方法。

Obviously, the for loop simply needs to go, and I need to set the entire range between $RowFound and $rowsTrans ... but how is that done?显然, for循环只需要去,我需要设置$RowFound$rowsTrans之间的整个范围......但这是如何完成的?

I know this is super old, but I found an even better way to do this with a one-liner.我知道这太旧了,但我找到了一种更好的方法来使用单衬纸来做到这一点。 This article sparked my months long journey to this single line... lol这篇文章激发了我几个月的单行旅程......大声笑

Measure-Command { $sheet.UsedRange.SpecialCells([Microsoft.Office.Interop.Excel.XlCellType]::xlCellTypeFormulas, 16).EntireRow.Delete() } #finds any row with an #N/A and blows it away

Referenced from here. 从这里引用。

The comment says what it does, but it searches the ENTIRE file for any cell with #N/A.注释说明了它的作用,但它会在整个文件中搜索带有 #N/A 的任何单元格。 I'm sure there is a way to make this even more efficient by narrowing to a single column.我确信有一种方法可以通过缩小到单个列来提高效率。 Hopefully this helps someone like me that couldn't get the range command to work!希望这可以帮助像我这样无法使用 range 命令的人!

BTW, this lowered my deletion times from 12-15 hours to 30 minutes on a ~30,000 line file.顺便说一句,这将我在大约 30,000 行文件上的删除时间从 12-15 小时减少到 30 分钟。

Construct a concatenated string containing all of the addresses as you run through the Range.Find loop.在运行Range.Find循环时构造一个包含所有地址的串联字符串。 Use that to define the Range object with the Range.EntireRow property to .Delete .使用它来定义Range 对象,其Range.EntireRow 属性.Delete

...Range("A2, A4, A10, A19").EntireRow.Delete

That uses a range object definition much like a Union of range objects.它使用范围对象定义,很像范围对象的 联合

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

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