在Excel中使用Find方法后,如何访问相邻的单元格数据?

时间:2018-08-02 17:24:51

标签: excel vba powershell

我正在使用Powershell在Excel电子表格中搜索电子邮件地址。找到给定的单元格值后,如何获得右侧的下一列?

我知道我可能必须按照链接中所述使用"address method",但是该属性引用的是布尔值。下面的代码使用的似乎是一个范围

这是我第一次将Powershell与Excel结合使用,如果有人可以演示如何获取$found,增加列值并获取内容,这不仅会很有帮助,我会问未来更聪明的问题。 ;)

   $Workbook = $Excel.Workbooks.Open($Source)
    ForEach ($Worksheet in @($Workbook.Sheets)) {
        # Find Method https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel
        $Found = $WorkSheet.Cells.Find($SearchText) #What
        If ($Found) {
            # Address Method https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-address-property-excel
            $BeginAddress = $Found.Address(0,0,1,1)
            #Initial Found Cell
            [pscustomobject]@{
                WorkSheet = $Worksheet.Name
                Column = $Found.Column
                Row =$Found.Row
                Text = $Found.Text
                Address = $BeginAddress
                Breach = $BreachValue
            }
            Do {
                $Found = $WorkSheet.Cells.FindNext($Found)
                $Address = $Found.Address(0,0,1,1)
                If ($Address -eq $BeginAddress) {
                    BREAK
                }
                [pscustomobject]@{
                    WorkSheet = $Worksheet.Name
                    Column = $Found.Column
                    Row =$Found.Row
                    Text = $Found.Text
                    Address = $Address
                    Breach = $BreachValue
            }                 
            } Until ($False)
        }
        Else {
            Write-Warning "[$($WorkSheet.Name)] Nothing Found!"
        }
    }
    $workbook.close($false)

1 个答案:

答案 0 :(得分:0)

  1. 我不确定为什么您声称Range.Address property是指布尔值-实际上,您是在引用$Found range 时使用它的第$BeginAddress = $Found.Address(0,0,1,1)行。
  2. Range.Offset property返回一个Range,它从指定的Range起偏移了一定数量的行和/或列。

因此$Found.Offset(0, 1)Range右侧的$Found 1列,然后您可以访问其.Column.Text,{{1} },等等。