Copy from Excel Workbook to Document from Word without Adding Reference

牧云@^-^@ 提交于 2020-01-25 08:07:05

问题


I'm looking to create a spell check macro for protected word documents. I'm more familiar with Excel VBA and I just created a similar project for protected spreadsheets so I attempted to follow the same logic. So far my code copies misspelled words from the office document, into a new excel workbook and then runs spellcheck, but I am having trouble pasting the new value back into the original word document. I can't have this require "adding a reference library" as this will need to be portable and run without end user intervention.

Here is what I have so far:

Sub SpellCheckDoc()

Dim lockedFields As Long
Dim unlockedFields As New Collection
For Each theFields In ActiveDocument.Fields
    If theFields.Locked = True Then
        lockedFields = lockedFields + 1
    Else
        unlockedFields.Add theFields
    End If
Next theFields
If lockedFields = ActiveDocument.Fields.Count Then Exit Sub

'Word
Dim objWord As Object    'Word.Application
Set objWord = GetObject(, "Word.Application")

'Excel
Dim objExcel As Object, objWB As Object
Set objExcel = CreateObject("Excel.Application")
Set objWB = objExcel.Workbooks.Add
objExcel.Visible = True
Set wb = objExcel.ActiveWorkbook
Set ws = wb.Worksheets("Sheet1")

For Each theFields In unlockedFields
    If CheckSpelling(theFields.Result.Text) = False Then
      theFields.Copy ' Select text from Word Doc

'Paste into new workbook and spellcheck
With ws
 .Range("A1").Select
 .Paste
 .Range("A1").CheckSpelling
 .Range("A1").Copy
End With

objWord.theFields.Paste ''' This line doesn't work

    End If
Next theFields
End Sub

回答1:


Change theFields.Result.Text. So you can do .CheckSpelling in Excel, then make theFields.Result.Text = .Range("A1").Text

Dim correctSpelling as String

With ws
 .Range("A1").Select
 .Paste
 .Range("A1").CheckSpelling
 correctSpelling = .Range("A1").Text
End With

    theFields.Result.Text = correctSpelling

    End If
Next theFields
End Sub


来源:https://stackoverflow.com/questions/59904167/copy-from-excel-workbook-to-document-from-word-without-adding-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!