【问题标题】:Powershell search excel document for exact matchPowershell 搜索 excel 文档以进行精确匹配
【发布时间】:2022-03-03 03:47:23
【问题描述】:

我正在使用 PowerShell 在文档中搜索关键字 (TTF),然后导入一些数据。我正在搜索几千个 excel 文档,大约一半的时候开始收集不需要的数据。

我的代码如下

$condition1 = "TTF"
$fs1 = $ws.cells.find($condition1)

当 excel 文档开始在文档开头的另一个单元格中使用“TTF All Day”时,它开始获取不需要的数据。

如何让 powershell 只准确查找“TTF”而不是“TTF”后跟更多字符。

谢谢

【问题讨论】:

  • 暂时我已在 $range = $ws.Range("A25:Q104") 中添加以删除任何超过 25 行的违规字符串。

标签: excel powershell


【解决方案1】:

尝试使用LookAt:=xlWhole 选项指定仅包含“TTF”的单元格:

$condition1 = "TTF"    
$fs1 = $ws.cells.find($condition1, LookAt:=xlWhole)

【讨论】:

    【解决方案2】:

    这会起作用

    $condition1 = "TTF"    
    $fs1 = [void]$ws.cells.find($condition1, [Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole)
    

    【讨论】:

      【解决方案3】:

      # This script illustrates how to use the Range.Find method 
      # with parameters to find exact match
      # ------------------------------------------------------------------------------------
      # Learn More:
      #    Range.Find Method: https://docs.microsoft.com/en-us/office/vba/api/Excel.Range.Find
      #    XlFindLookIn: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfindlookin
      #    XlLookAt: https://docs.microsoft.com/en-us/office/vba/api/excel.xllookat
      
      # Open Excel
      $Excel = New-Object -ComObject Excel.Application
      $Excel.Visible=$false
      $Excel.DisplayAlerts=$false
      
      # Open Spreadsheet you want to test
      $xlSource = "C:\Temp\YourSpreadsheetNameGoesHere.xlsx"
      $xlBook = $Excel.Workbooks.Open($xlSource)
      $xlSheet = $xlBook.worksheets.item("SheetNameGoesHere")
         
      # What you want to seach                 
      $searchString = "John Smith"
          
      # Column or Range you want to seach
      $searchRange = $xlSheet.Range("A1").EntireColumn
          
      # Search
      $search = $searchRange.find($searchString,
                                  $searchRange.Cells(1,1),
                                  [Microsoft.Office.Interop.Excel.XlFindLookIn]::xlValues,
                                  [Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole
                              )
      
      # NOT FOUND
      if ($search -eq $null) {
              
      
          Write-Host "Not found"
      
      }
      
      else { # FOUND
      
          Write-Host "Found at row #" -NoNewline
          Write-Host $search.Row
      
      }
      
      # Close Objects
      if ($xlBook) { $xlBook.close() }
      if ($Excel) { $Excel.quit() }

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多