M
M
Maxim Obukhov2019-12-22 16:25:44
PowerShell
Maxim Obukhov, 2019-12-22 16:25:44

How to delete a large number of columns in excel powershell?

I need to process incoming excel files. It is certainly known that they have 35 significant columns, no more (thousands of rows). But sometimes it is not clear how the generated files in which there are several hundred columns come. Accordingly, I want to delete all columns to the right of the 35th. Simple enumeration - works, but very, very long:

$wb = $Excel.Workbooks.Open($ExcelFile)
$ws = $wb.Worksheets.Item(1)
$used = $ws.usedRange
$lastrow = $used.SpecialCells(11).row
$lastcol = $used.SpecialCells(11).column
for ($i = $lastcol; $i -ge 35; $i--) {
  [void]$ws.Columns($i).Delete()
}

How can this be accelerated? I tried to make a Range and delete it already:
$allcol = $ws.Range($ws.Cells.Item(35, 1), $ws.Cells.Item($lastcol,$lastrow))
$allcol.Delete()

But the columns are not deleted for some reason. CHADNT? Maybe there is some other option? Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
azarij, 2019-12-22
@azarij

I got it like this:

$lastusedcolumn = $ws.Cells.item(1,($ws.columns.Count)).end(-4159).column
foreach ($item in ($lastusedcolumn..36)) {
    $item
    $ws.cells.item(1,$item).entirecolumn.delete()
    
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question