用于复制excel数据范围的宏,因为表到单词超出了边距

时间:2014-11-14 05:49:33

标签: excel vba excel-vba

我想编写宏来将表从excel复制到word。它应该保持格式化并且必须自动适应单词。粘贴到单词时,表格不应超出范围。

Dim wdApp As Object
Dim wd As Object

On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
    Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set wd = wdApp.Documents.Add

wdApp.Visible = True

Sheets("Sheet1").Select
Range("A1:E36").Select
Selection.Copy

wdApp.Selection.PasteExcelTable False, False, False

以上代码更糟糕。它以表格为单位复制excel数据范围。然而,表格超出了word文档的边缘。 Excel中的数据 - Source Data in excel 复制后Word中的数据 - After Copy to Word

4 个答案:

答案 0 :(得分:1)

添加到最后

wd.Tables(1).AutoFitBehavior wdAutoFitWindow

答案 1 :(得分:1)

试试这个:

wdApp.Selection.PasteExcelTable False, True, False   'causing losing excel formatting

<强>追加:

'change fileformat and filename as per your need

wdApp.Selection.PasteExcelTable False, False, False
wd.SaveAs Filename:="demo.docm", FileFormat:=wdformatdocm
wd.Tables(1).AutoFitBehavior wdAutoFitContent 'you may try wdAutoFitWindow as well

答案 2 :(得分:0)

尝试

wd.Tables(1).Range.ParagraphFormat.SpaceAfter = 0

答案 3 :(得分:-1)

在wdAutoFitWindow

周围放置一个括号