vba 将excel数据范围复制为表格到单词的宏超出边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26923745/
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
Macro to copy excel range of data as table to word goes outside margins
提问by user660232
I want to write macro to copy table from excel to word. It should maintain formatting and must auto-fit to word. Table should not go out of range when pasted to word.
我想编写宏将表格从excel复制到word。它应该保持格式并且必须自动适应word。粘贴到 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
Above code wors. It copies excel range of data as table to word. However table goes outside margins of word document.
Data in Excel - Data in Word after Copy -
上面的代码很糟糕。它将excel范围的数据作为表格复制到单词。但是表格超出了word文档的边距。Excel 中的数据 - 复制后 Word 中的数据 -
采纳答案by Dale M
Add to the end
添加到最后
wd.Tables(1).AutoFitBehavior wdAutoFitWindow
回答by ZAT
Try this:
尝试这个:
wdApp.Selection.PasteExcelTable False, True, False 'causing losing excel formatting
Appended:
附加:
'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
回答by xlnc
Try
尝试
wd.Tables(1).Range.ParagraphFormat.SpaceAfter = 0
回答by user4886100
Put a bracket around wdAutoFitWindow
在 wdAutoFitWindow 周围放一个括号