[英]How to import range as array, from Excel into Word document
I'm working on a VBA Word Macro to create a document with personalized headers.我正在使用 VBA Word 宏来创建带有个性化标题的文档。 I have a spreadsheet with the text to be inserted in the Headers (every row shall be inserted on an individual page).
我有一个电子表格,其中包含要插入标题的文本(每一行都应插入一个单独的页面)。
To do so, I want to import the data from spreadsheet as an Array
into Word, in order to get those texts in place.为此,我想将电子表格中的数据作为
Array
导入到 Word 中,以便将这些文本放置到位。
I wrote a piece of code to open the spreadsheet and get a pre-defined range using Select
method;我写了一段代码来打开电子表格并使用
Select
方法获得一个预定义的范围; I get an error on trying to pass this Selection
to a Range
object.尝试将此
Selection
传递给Range
object 时出现错误。
The error message is Runtime Error 13: Incompatible types
.错误消息是
Runtime Error 13: Incompatible types
。
I added an If
loop to assure that the Selection
is not empty, and it wasn't, for every time I ran the code.我添加了一个
If
循环以确保Selection
不为空,而且在我每次运行代码时它都不是。
Sub main()
'Main procedure
Dim app_Excel As Excel.Application
Set app_Excel = CreateObject("Excel.Application")
Dim wbk_srce As Workbook
Set wbk_srce = app_Excel.Workbooks.Open("C:\0_portolon\Dias.xlsm", , False)
Dim wsh_srce As Worksheet
Set wsh_srce = wbk_srce.Worksheets(3)
wsh_srce.Activate
cell_1 = CStr("A1")
cell_2 = CStr("D216")
Dim header_range As Range
wsh_srce.Range(cell_1, cell_2).Select
If Selection = Empty Then
Debug.Print ("error")
Else
Debug.Print ("good")
End If
Set header_range = Selection '<---Error
Dim header_array() As Variant
'header_array = header_range.Value
'Call add_readers
End Sub
Note: I added only the Microsoft Excel 16.0 Object Library to VBA Word.注意:我只将 Microsoft Excel 16.0 Object 库添加到 VBA Word。
How can I make this work?我怎样才能使这项工作?
Thanks in advance,提前致谢,
Tiago蒂亚戈
Both Word and Excel have a Selection
object so when you refer to a selection in Excel you need to qualify it by prefixing it with your Excel Application variable, ie app_Excel.Selection
. Word 和 Excel 都有一个
Selection
object,因此当您引用 Excel 中的一个选择时,您需要通过在它前面加上您的 Excel 应用程序变量(即app_Excel.Selection
)来限定它。
You also need to do this with other objects that both applications have in common such as Range
.您还需要对两个应用程序共有的其他对象执行此操作,例如
Range
。 Word will understand Dim header_range As Range
as being a Word.Range
, so assigning a selection in Excel to it isn't going to work. Word 会将
Dim header_range As Range
理解为Word.Range
,因此将 Excel 中的选择分配给它是行不通的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.