Powershellfindexcel单元格引用

我正在使用下面的PowerShell代码来search一个string的Excel文档,并返回true或false取决于它的发现。

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

我希望能够得到string的单元格引用,如果它find,但我不能弄明白,或在谷歌上find答案。 你能帮我吗?

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

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

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

要继续search所有出现的内容,请使用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)) } } 

由于缺less大量代码,因此很难提供更多的一般性内容。 我用自己的testing环境填补了缺失的信息。