简体   繁体   中英

Macro to copy excel range of data as table to word goes outside margins

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.

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 - Excel中的源数据 Data in Word after Copy - 复制到Word之后

添加到最后

wd.Tables(1).AutoFitBehavior wdAutoFitWindow

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

尝试

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

将括号放在wdAutoFitWindow周围

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM