vba 将值从 Excel 中的范围复制到 Word 中的书签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17866310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:25:20  来源:igfitidea点击:

Copying values from range in Excel to bookmark in Word

excelexcel-vbavba

提问by user2620058

The following code copies a single value into a bookmark in Word. I need it to copy a range of values like "A6:G20".

以下代码将单个值复制到 Word 中的书签中。我需要它来复制一系列值,如“A6:G20”。

Sub test()
Dim objWord As Object
Dim ws As Worksheet

Set ws = Workbooks("Portfolio1").Sheets("Print")
Set objWord = CreateObject("Word.Application")

objWord.Visible = True
objWord.Documents.Open "D:Q.docx" ' change as required

With objWord.ActiveDocument
 .Bookmarks("monthtable").Range.Text = ws.Range("C6").Value ' here I need range of values to be selected instead of a single cell
End With
Set objWord = Nothing
End Sub 

回答by Andy G

If suitable, you could copy and paste the range:

如果合适,您可以复制并粘贴范围:

Range("A6:G20").Copy
.Bookmarks("monthtable").Range.PasteExcelTable False, False, False

There are a number of other Paste methods if you don't wish to paste as an Excel table. Use Word's VB Editor to discover these, or the Word Macro Recorder.

如果您不想粘贴为 Excel 表格,还有许多其他粘贴方法。使用 Word 的 VB 编辑器或 Word 宏录制器来发现这些。

回答by Joe

This is of course the important part:

这当然是重要的部分:

With objWord.ActiveDocument    
.Bookmarks("monthtable").Range.Text = ws.Range("C6").Value ' here i need range of values to be selected instead of a single cell
End With

Here you need to cycle through the ws.Range("..."), and for each cell in that range, concatenatethat value onto the .Bookmarks.Range.Text value (Rather than setting it equal, which would overwrite). It's probably a good idea to first concatenate this into a string variable and then set the bookmark to that string variable's value, since that would avoid some potential interop issues.

在这里,您需要循环遍历 ws.Range("..."),并且对于该范围内的每个单元格,将该值连接到 .Bookmarks.Range.Text 值上(而不是将其设置为相等,否则会覆盖)。首先将其连接到一个字符串变量中,然后将书签设置为该字符串变量的值可能是一个好主意,因为这将避免一些潜在的互操作问题。