通过 PowerShell 将格式化的文本添加到 Word 自动更正

通过 PowerShell 将格式化的文本添加到 Word 自动更正

我们使用的是 Word 2010,并且有一个 PowerShell 脚本,该脚本可以读取 Word docx 文件中的表格并使用它来填充自动更正词典。它适用于不需要格式化的常规条目;但它会在需要使用 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)

答案1

代码看起来正确,但不幸的是异常细节含糊不清,没有帮助。我能想到的唯一可能错误是 AddRichText 可能不喜欢传递单元格范围而不是段落范围,而这正是它所期望的。尝试更改它,看看是否有帮助。

相关内容