通过 PowerShell 读取突出显示的 Excel 单元格

问题描述 投票:0回答:1

我的工作表如下所示: (https://i.sstatic.net/oJyJ6PA4.png) 我想自动确定突出显示哪个单元格并使用 PowerShell 获取其值。在这种情况下它将是“3”(来自 F5 单元格)。

这是我的努力:

#Define the path to the Excel file $excelFilePath = "C:\Users\Documents\Book3.xlsx"

$objExcel=New-Object -ComObject Excel.Application $objExcel.Visible=$True $workbook=$objExcel.Workbooks.Open($excelFilePath) $sheet = $workbook.Worksheets.Item('Sheet1') $sheet.activate()

#Read data from a specific cell based on row number and column number and store it in a variable called $value:
#$value = $Worksheet.Cells.Item($rowNumber,$columnNumber).text

#Initialize an array to hold values of highlighted cells
    $highlightedValues = @()

#Define the range of rows and columns to check 
    $startRow = 1
    $endRow = 10
    $columns = 'A','B','C','D','E','F'  # Columns A to F
    for ($rowNumber = $startRow; $rowNumber -le $endRow; $rowNumber++) { Get the cell using row number and column letter
            $cell = $worksheet.Cells.Item($rowNumber, $columnLetter)

#Check if the cell's interior color is not automatic (not highlighted) 
    if ($cell.Interior.ColorIndex -ne -4142) {  # -4142 represents xlNone Add the cell value to the array
                $highlightedValues += $cell.Value()
            }
        } Print highlighted cell values to the PowerShell console if ($highlightedValues.Count -gt 0) { Write-Host "Highlighted cell values:"
        $highlightedValues | ForEach-Object { Write-Host $_ } else { Write-Host "No highlighted cells found."
    }


#Save the excel workbook: $Workbook.Save()

#Quit from excel application:

有更有效的方法吗?感谢任何建议。

excel powershell batch-processing
1个回答
0
投票

最有效的方法是不要迭代单元格并让 Excel 自己计算结果。

解决方案之一是将名称添加到工作簿中

GetMyInfo=TOROW(MAP(Sheet1!A1:G11,LAMBDA(itm,IF(GET.CELL(63,itm)=0,1/0,itm))),2)

此计算提供单元格中的值数组以及公式中引用的范围的非自动背景颜色。您可以修改公式以添加范围作为参数。

此名称可以永久添加到目标工作簿中,也可以在脚本中动态添加(由于某些限制,我们无法避免使用名称来执行此计算)。

然后在ps脚本中评估它

$cells = $objExcel.Evaluate("=GetMyInfo")

询问我您的进一步需求。

© www.soinside.com 2019 - 2024. All rights reserved.