从Excel工作簿复制到Word中的文档,而无需添加参考 [英] Copy from Excel Workbook to Document from Word without Adding Reference

查看:135
本文介绍了从Excel工作簿复制到Word中的文档,而无需添加参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为受保护的Word文档创建一个拼写检查宏.我对Excel VBA更加熟悉,我刚刚为受保护的电子表格创建了一个类似的项目,因此我尝试遵循相同的逻辑.到目前为止,我的代码将Office文档中拼写错误的单词复制到新的excel工作簿中,然后运行拼写检查,但是我很难将新值粘贴回原始word文档中.我不能要求添加参考库",因为这将需要可移植并且可以在没有最终用户干预的情况下运行.

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

推荐答案

更改theFields.Result.Text.因此,您可以在Excel中执行.CheckSpelling,然后将theFields.Result.Text = .Range("A1").Text

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

这篇关于从Excel工作簿复制到Word中的文档,而无需添加参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆