Powershell 找到 excel 单元格引用

Powershell find excel cell reference

我正在使用以下 powershell 代码在 excel 文档中搜索字符串,并根据是否找到 return true 或 false。

if (test-path $filePath) {
$wb = $xl.Workbooks.Open($filePath)
if ([bool]$xl.cells.find("German")) {$found = 1}
}

如果找到字符串,我希望能够获取该字符串的单元格引用,但我无法弄清楚或在 google 上找到答案。你能帮忙吗?

虽然有一种方法可以在整个工作簿中搜索值,但通常会在工作表上执行 Range.Find method。您正在为工作簿设置一个 var,但仍使用该应用程序作为搜索。您应该从工作簿中获取要搜索的工作表,并将其用作查找操作的目标。

以下是对您的 PS1 的一些修改建议。

$filePath = "T:\TMP\findit.xlsx"
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $true
if (test-path $filePath) {
$wb = $xl.Workbooks.Open($filePath)
$ws = $xl.WorkSheets.item("sheet1")
if ([bool]$ws.cells.find("German")) 
    {
    $found = 1
    write-host $found
    write-host $ws.cells.find("German").address(0, 0, 1, 1)
    }
}

要继续搜索所有匹配项,请使用 Range.FindNext method 直到循环回到原始单元格地址。

$filePath = "T:\TMP\findit.xlsx"
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $true
if (test-path $filePath) {
$wb = $xl.Workbooks.Open($filePath)
$ws = $wb.WorkSheets.item("sheet1")

$rc1 = $ws.cells.find("German")
if ($rc1) 
    {
    $found = 1
    $addr = $rc1.address(0, 0, 1, 0)
    do
        {
        $rc1 = $ws.cells.findnext($rc1)
        write-host $rc1.address(0, 0, 1, 0)
        } until ($addr -eq $rc1.address(0, 0, 1, 0))
    }
}

很难提供比一般性更多的内容,因为您的代码缺失太多。缺失的信息我用自己的测试环境补上了