Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting cell range from Excel using Powershell

I was trying to select from A55 to the last row that is filled from column A in Excel using Powershell script.

My first script worked perfectly which is:

$lastRow = $ivWorksheet.Cells.Item($ivWorksheet.Rows.Count, "A").End(3).Row
$ivRange = $ivWorksheet.Range("A55:A$lastRow")

However when I changed above into below, it was not working.

$startRow = 55
$lastRow = $ivWorksheet.Cells.Item($ivWorksheet.Rows.Count, "A").End(3).Row
$ivRange = $ivWorksheet.Range("A$startRow:A$lastRow")

I was expecting both script to have same result, but the latter one did not work. Could you please advise what the reason is?

like image 542
Sangwon Lee Avatar asked Mar 13 '26 09:03

Sangwon Lee


1 Answers

$startRow:A is being interpreted as a variable in your second attempt and because that variable isn't defined, it is expanded to null:

$startRow = 55; $lastRow = 123
"A$startRow:A$lastRow" # => A123

You need to use ${ } to delimit it, in other words, to indicate where the variable starts and where it ends so PowerShell can resolve it correctly. See Variable names that include special characters for more information.

$startRow = 55; $lastRow = 123
"A${startRow}:A$lastRow" # => A55:A123
like image 132
Santiago Squarzon Avatar answered Mar 16 '26 03:03

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!