user3657339
user3657339

Reputation: 627

Extract sections from range found in word document

Below code works fine, we got start and end point which needs to be extracted but im not able to get range.set/select to work

I'm able to get the range from below, just need to extra and save it to CSV file...

$found = $paras2.Range.SetRange($startPosition, $endPosition) - this piece doesn't work.

$file = "D:\Files\Scan.doc"
$SearchKeyword1 =  'Keyword1'
$SearchKeyword2 =  'Keyword2'    

$word = New-Object -ComObject Word.Application
$word.Visible = $false
$doc = $word.Documents.Open($file,$false,$true)
$sel = $word.Selection 
$paras = $doc.Paragraphs 
$paras1 = $doc.Paragraphs
$paras2 = $doc.Paragraphs

foreach ($para in $paras) 
{ 
    if ($para.Range.Text -match $SearchKeyword1)
    {
        Write-Host $para.Range.Text
        $startPosition = $para.Range.Start
    }
} 
foreach ($para in $paras1) 
{ 
    if ($para.Range.Text -match $SearchKeyword2)
    {
        Write-Host $para.Range.Text
        $endPosition = $para.Range.Start
    }
} 

Write-Host $startPosition
Write-Host $endPosition
$found = $paras2.Range.SetRange($startPosition, $endPosition)

# cleanup com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Upvotes: 0

Views: 632

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25693

This line of code is the problem

$found = $paras2.Range.SetRange($startPosition, $endPosition)

When designating a Range by the start and end position it's necessary to do so relative to the document. The code above refers to a Paragraphs collection. In addition, it uses SetRange, but should only use the Range method. So:

$found = $doc.Range.($startPosition, $endPosition)

Upvotes: 1

Related Questions