2

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

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

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

4

1 回答 1

4

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

以下是对您的 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 方法,直到您循环回原始单元格地址。

$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))
    }
}

由于缺少很多代码,因此很难提供比一般性更多的内容。我已经用自己的测试环境填写了缺失的信息。

于 2015-09-30T13:17:30.533 回答