首页 > 解决方案 > 将文本从 Excel 粘贴到 Word 在特定位置 VBA

问题描述

我正在尝试将我已经建立的变量(在这种情况下变量是 QN_number)放入特定位置的 word 文档中,我过去曾这样做过,除了我将整个表格放入 word 中,因此代码不同。我一直无法找到一种直接使用变量名的方法,这将是首选,而不是每次都必须引用一个范围。此外,我现在使用的方法效果不佳,因为它确实粘贴在正确的位置,但它会将与变量关联的单词粘贴为可以移动和调整大小的选择框。我想像文档中的任何其他文本一样粘贴。这是我现在正在使用的代码。有没有人有什么建议?

Sub Export_Excel_To_Word()

'Connect to M-Word
Dim wordApp As Word.Application
Set wordApp = New Word.Application
wordApp.Visible = True
Dim wordDoc As Word.Document

i = 0

'Exits loop when QN#s are finished
Do
If Cells(i + 2, 2) = "" Then
Exit Do
Else: End If


'Opens the Template Word Document For Discus Complaints
Set wordDoc = wordApp.Documents.Open(File_Name)


 'Places the QN# in the Word Document
 With Worksheets("Data").Cells(i + 2, 2)
 .Copy
wordDoc.Application.Selection.Find.Execute "Complaint Description:" '***Places after a specfic word
wordApp.Selection.MoveDown Unit:=wdLine, Count:=-1, Extend:=wdMove '***Moves the placement up a line
wordApp.Selection.TypeParagraph
'wordDoc.Paragraphs.Add
wordApp.Selection.Paste
End With
end sub

标签: excelvba

解决方案


我最终找到了自己问题的答案

首先定义你的变量,然后使用下面的代码

'Places the QN# in the Word Document
wordDoc.Application.Selection.Find.Execute "Complaint Description:" '***Places after a specfic word
wordApp.Selection.MoveDown Unit:=wdLine, Count:=-1, Extend:=wdMove '***Moves the placement up a line
wordApp.Selection.TypeText (QN_number)

推荐阅读