PowerShell을 통해 Word 자동 고침에 서식이 지정된 텍스트 추가 열은 서식있는 텍스트

우리는 Word 2010을 사용 중이며 Word docx 파일의 테이블을 읽고이를 사용하여 자동 고침 사전을 채우는 PowerShell 스크립트를 사용합니다. 그것은 형식화 할 필요가없는 일반 항목에 대해 작동합니다. 그러나 AddRichText 메서드를 사용해야하는 항목은 중단됩니다. 이 오류를 제공합니다.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x800A16DC): Reques
ted object is not available.
   --- End of inner exception stack trace ---
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParamet
ers)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInf
o culture, String[] namedParams)
   at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)

PowerShell의 코드는 다음과 같습니다. Word 문서의 3 열 테이블에서 읽고이를 사용하여 자동 고침을 채 웁니다. 첫 번째 열은 이름을 가지며, 다음 열은 값을 가지며 마지막 열은 서식있는 텍스트 (서식 지정 됨)를 나타내는 X 일 수 있습니다.

$objWord = New-Object -Com Word.Application

$filename = 'D:\Codes.docx'
$objDocument = $objWord.Documents.Open($filename)

$LETable = $objDocument.Tables.Item(1)
$LETableCols = $LETable.Columns.Count
$LETableRows = $LETable.Rows.Count

$word = New-Object -ComObject word.application
$word.visible = $true
$entries = $word.AutoCorrect.entries

Write-output "Starting to write... "

for($r=1; $r -le $LETableRows; $r++) {
    $replace = $LETable.Cell($r,1).Range.Text
    $replace = $replace.Substring(0,$replace.Length-2)
    $with = $LETable.Cell($r,2).Range.Text
    $withRange = $LETable.Cell($r,2).Range
    $with = $with.Substring(0,$with.Length-2)
    $format = $LETable.Cell($r,3).Range.Text
    $format = $format.Substring(0,$format.Length-2)

    Try
        {
            if($format -eq "X") {
                $entries.addrichtext($replace, $withRange) | out-null
            }
            else {
                $entries.add($replace,$with) | out-null
            }
        }
    Catch [system.exception]
        {
          Write-Host $_.Exception.ToString()
        }
}
$objDocument.Close()
$objWord.Quit()

 $word.Quit()

 #$word = $null

 [gc]::collect()

 [gc]::WaitForPendingFinalizers()

# Stop Winword Process
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)



답변

코드가 정확하고 유감스럽게도 예외 세부 사항이 모호하고 도움이되지 않습니다. 내가 생각할 수있는 유일한 것은 AddRichText가 예상 한 단락 범위 대신 셀 범위를 전달하는 것을 좋아하지 않을 수도 있다는 것입니다. 그것을 변경하고 도움이되는지 확인하십시오.


답변