如何使用VB将表从excel复制到word

时间:2013-05-30 15:26:31

标签: excel-vba vba excel

我正在尝试使用来自我的excel(.xlsm)的数据使用VB宏自动生成word文档(.docm)。

目前,我可以将excel的部分信息复制到word文档中。 问题是我找不到将表信息传递给单词书签的解决方案。

Sub Word()

Dim wdApp As Word.Application
Dim WDDoc As Word.Document
Dim BMRange As Word.Range
Dim cliente As Range
Dim CPE As Range
Dim localidade As Range
Dim numproposta As Range
Dim DIRECT, saveAsName, data As String
Dim table1 As Table

Set wdApp = CreateObject("Word.Application") 'Create an instance of word
Set WDDoc = wdApp.Documents.Open("C:\Users\PT13217294\test.docm") 'Open word file
wdApp.Visible = True

'excel ranges
'Windows(shtname).Activate

Set cliente = Sheets("Dados").Range("C10")
Set CPE = Sheets("Dados").Range("C15")
Set localidade = Sheets("Dados").Range("C13")
Set table1 = Sheets("Cálculos").Range("B5:K17")

'word's bookmark

'cabeçalho
 ActiveDocument.Bookmarks("cliente4").Range.Text = cliente

'rodapé
ActiveDocument.Bookmarks("num_proposta4").Range.Text = numproposta

 'corpo texto
 Set BMRange = WDDoc.Goto(What:=wdGoToBookmark, Name:="cliente1")
 BMRange.Text = cliente

 Set BMRange = WDDoc.Goto(What:=wdGoToBookmark, Name:="Table")
 BMRange.Text = table1

'Guardar word na pasta das propostas
With wdApp.ActiveDocument
saveAsName = "C:\Users\PT13217294\test.docm"
ActiveDocument.SaveAs Filename:=saveAsName
wdApp.Quit
End With

Set BMRange = Nothing
Set WDDoc = Nothing
Set wdApp = Nothing

我该怎么做才能解决这个问题? 提前谢谢,

安德烈

2 个答案:

答案 0 :(得分:1)

您无法将Excel Range Object(代码中为table1)分配给Word Range.Text Properties。在这种情况下,我们通常需要在两个应用程序之间复制>>粘贴。

因此,您需要执行以下操作:

'....your code here
Set BMRange = WDDoc.Goto(What:=wdGoToBookmark, Name:="Table")
'new code for you
    table1.Copy
    BMRange.Paste
'rest of your code
'Guardar word na pasta das propostas
With wdApp.ActiveDocument
'...and so on

如果需要,您需要在粘贴时尝试表格形成。 上述解决方案经过了试验和测试。

答案 1 :(得分:0)

使用Kaz的建议(Option Explicit可以防止出现此类错误)后,一旦复制了表格,就可以尝试这样的事情(未经测试):

Dim wdRange as Object
Set wdRng = WDDoc.Bookmarks("Table").Range
wdApp.Goto(What:=wdGoToBookmark, Name:="Table")
wdApp.Selection.PasteAndFormat wdTableOriginalFormatting '## Modify as needed

在粘贴新表格形状之前,您可能需要添加一些逻辑来删除现有的表格形状。

我认为如果你删除,那么可能也需要这样做(我的示例Excel中有这个 - > Word宏,但是我使用它已经有一段时间了):

wdApp.Selection.Bookmarks.Add "Table", wdRng