如何使用VB代码将MSExcel单元格中的值复制到MSWord文件中的字段中?
我需要在MS Word 2003中有一个VB代码,复制Excel文件中的特定单元格并将其粘贴到Word(归档)中。 以下是我所做的,结果是错误的。
Sub cmdGetNumber()
Dim XL As Object
Dim WBEx As Object
Dim ExelWS As Object
Dim appwd As Object
Dim wdApp As Word.Application
''''
'On Error GoTo OLE_ERROR
Set XL = CreateObject("Excel.Application")
Set wdApp = CreateObject("Word.Application")
'Open Excel document
Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
Set ExelWS = WBEx.Worksheets("Sheet1")
XL.Visible = True
'appwd.Visible = True
ExelWS.Range("c2").Select
'Selection.Copy
'wdApp.Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteMetafilePicture
'wdApp.Documents.Save
Set wdApp = Nothing
Set ExelWS = Nothing
Set WBEx = Nothing
End Sub
I need to have a vb code in ms word 2003 that copy a a specific cell in excel file and paste it in word (filed). Below is what I have done and it result in error.
Sub cmdGetNumber()
Dim XL As Object
Dim WBEx As Object
Dim ExelWS As Object
Dim appwd As Object
Dim wdApp As Word.Application
''''
'On Error GoTo OLE_ERROR
Set XL = CreateObject("Excel.Application")
Set wdApp = CreateObject("Word.Application")
'Open Excel document
Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
Set ExelWS = WBEx.Worksheets("Sheet1")
XL.Visible = True
'appwd.Visible = True
ExelWS.Range("c2").Select
'Selection.Copy
'wdApp.Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteMetafilePicture
'wdApp.Documents.Save
Set wdApp = Nothing
Set ExelWS = Nothing
Set WBEx = Nothing
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于该宏位于 Word 中,因此您无需显式打开 Word 实例。 您只需执行
Documents.Add
即可添加新文档,或执行Documents.Open
来打开现有文档。试试这个:
上面的代码将打开您的 Excel 文件,复制单元格 C2,然后打开一个新的 Word 文档,并将其粘贴到那里。
我看到您在问题中提到了
(filed)
。 您指的是Field
还是File
? 如果它是Field
那么您可能需要将Selection.Paste
替换为相关字段名称Since this macro is in Word, you don't need to explicitly open a word instance. You can just do
Documents.Add
to add a new document, orDocuments.Open
to open an existing one.Try this:
The above code will open your excel file, copy the cell C2, then open a new word document, and paste it there.
I see you have mentioned a
(filed)
in your question. Did you mean aField
or aFile
? If it is aField
then you may want to replaceSelection.Paste
with the relevant field name