简体   繁体   English

如何在 PowerShell 中迭代 Excel 范围?

[英]How to iterate over an Excel Range in PowerShell?

This might be easy, but I am really struggling to write code that accomplishes this!这可能很容易,但我真的很难编写完成此任务的代码!

Just as a concept, I want to be able to write down a range of Excel cells in Powershell, and then iterate over each cell with a loop, and sum the value in each cell.只是作为一个概念,我希望能够在Powershell中写下Excel个单元格的范围,然后用循环遍历每个单元格,并对每个单元格中的值求和。

$range="A1:B2".Split(":")

$startrow= $range[0] -replace "[^0-9]" #equals 1
$startcol= $range[0] -replace "[^A-Z]" #equals "A"
$maxrow= $range[1] -replace "[^0-9]" #equals 2
$maxcol= $range[1] -replace "[^A-Z]" #equals "B"
$row = $startrow; $col = $startcol; $value = 0
while($col -le $maxcol){
$row = $startrow
    while($row -le $maxrow){
    $cellValue = [int]$ws_test.Cells.Item($row,$col).Text
    $value = $value + $cellValue
    $row++
    }
$col++
}

This is as far as I got.据我所知。 The nested while loop would work if I could convert the macros $startcol and $maxcol to integers, but I can't figure out how to do that (ex: convert "A" to 1, or "AA" to 27).如果我可以将宏 $startcol 和 $maxcol 转换为整数,嵌套的 while 循环将起作用,但我不知道该怎么做(例如:将“A”转换为 1,或将“AA”转换为 27)。

Is there another method I could look into to accomplish this?我可以研究另一种方法来实现这一目标吗? I'm pretty new to PowerShell and have been struggling with this for the last few days.我对 PowerShell 很陌生,最近几天一直在努力解决这个问题。

You can define the range of cells on the worksheet, then iterate over each cell in the range:您可以定义工作表上的单元格范围,然后遍历该范围内的每个单元格:

    Foreach ($cell in $worksheet.Range("A1:B10")) {
        # Process cell values here
    }

https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.range https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.range

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

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