简体   繁体   中英

Macro to Copy Content from Excel and paste in MS Word

I have an idea for a report generation macro from Excel to Word.

The report format in excel is as below .

Excel中报告格式的模拟屏幕

The report in word

There is an existing code as below to copy and paste in word . But is there a way to format it as in the above screenshot?

Sub TestingMacAndWin()
Dim appWD As Object
Dim wddoc As Object

On Error Resume Next
Set appWD = GetObject(, "Word.application")    'gives error 429 if Word is not open
If Err = 429 Then
    Set appWD = CreateObject("Word.application")    'creates a Word application
    Err.Clear
End If

Set wddoc = appWD.Documents.Add
appWD.Visible = True

With appWD.ActiveDocument.PageSetup
    .TopMargin = appWD.InchesToPoints(0.3)
    .BottomMargin = appWD.InchesToPoints(0.3)
    .LeftMargin = appWD.InchesToPoints(0.3)
    .RightMargin = appWD.InchesToPoints(0.3)
End With

Sheets("Sheet1").Range("A1:D2").CopyPicture xlScreen
appWD.Selection.Paste

appWD.Activate

End Sub

source : http://www.rondebruin.nl/mac/mac030.htm

Paste your data in. Stop your Macro ( stop command will do that), then record your formatting ( Alt + T, M, R ). Go get the recorded macro, and paste it into your macro, fixing the object you are working on (eg .ActiveDocument to AppWD.ActiveDocument though you probably don't have to do).

COM have changed over the years, and is now recommended to GetObject the Document object, not the Application Object. Among other minor things it elininates reference counting problems on the Application object, this where the application doen't exit when closed.

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