PDA

View Full Version : [SOLVED:] can I edit in word after export data from excel



maghari
04-06-2021, 02:28 PM
hello
I'm asking if it's possible to edited the table in word file after export from excel file , actually my code export the table from excel to word as image ,so I can't change any value and I have a macro to export to word
I attached two simple files
any suggestion I will truly appreciate

gmayor
04-06-2021, 09:48 PM
Word is not a graphics editor, so if you paste as an image you will not be able to edit it in Word. Paste as html instead e.g. as follows. Note that the code is over-complicated by the fact that your document has a graphic image which needs to be replaced with a table.


Option Explicit'Graham Mayor - https://www.gmayor.com - Last updated - 07 Apr 2021
Sub Export_Table_Word1()

'Name of the existing Word doc.
Const stWordReport As String = "test.docx"

'Word objects.
Dim wdApp As Object
Dim wdDoc As Object
Dim wdbmRange As Object

'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range

'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("sheet1")
Set rnReport = wsSheet.Range("Table1")

'Initialize the Word objects. It's much faster if Word is already open using this method.
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport) 'note the path separator!

'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
If wdDoc.InlineShapes.Count > 0 Then
wdDoc.InlineShapes(1).Select
wdDoc.InlineShapes(1).Delete
Set wdbmRange = wdApp.Selection.Range
wdbmRange.Bookmarks.Add "InsertHere"
End If

'Remove the previous table if present
Set wdbmRange = wdDoc.Bookmarks("InsertHere").Range
If Len(wdbmRange) > 0 Then wdbmRange.Cut
Set wdbmRange = wdApp.Selection.Range

'Turn off screen updating.
Application.ScreenUpdating = False

'Copy the report to the clipboard.
rnReport.Copy

'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
wdbmRange.PasteExcelTable False, False, False
Set wdbmRange = wdbmRange.tables(1).Range
wdbmRange.End = wdbmRange.End + 2
wdbmRange.Bookmarks.Add "InsertHere"


'Save and close the Word doc.
With wdDoc
.Save
'.Close
End With

'Quit Word.
'wdApp.Quit

'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing

'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With

MsgBox "The report has successfully been " & vbNewLine & _
"transferred to " & stWordReport, vbInformation
End Sub

maghari
04-07-2021, 01:05 AM
thanks so much it's better :clap: