Select range copy paste run macro clear loops till blank column, - vba

I want to copy column A of karai1.xlsx to column A of wipbuj2.xlsx and then run the following macro to copy information to a Word document. Then I want to repeat this by copying column B of karai1.xlsx to column A of wipbuj2.xlsx and run the copy-to Word macro. Then column C of karai1.xlsx, etc, until I reach a blank column. Below is my attempt at copying the first column.
What i need is: copy column from workbook karai1.xlsx paste in workbook wipbuj2.xlsx in A(1st column) run macro/ code following
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("Sheet5").Select
Range("A1:g39").Select
Selection.Copy
wdApp.Selection.PasteExcelTable False, False, True
wd.SaveAs
wd.Close
wdApp.Quit
then copy from column 2 from workbook karai1.xlsx paste in wippuj2.xlsx A column run macro run this loop till blank column in sheet karai1.xlsx .
Please help.
this is the code i was working
enter code here
Workbooks.Open Filename:="C:\Users\DO\Desktop\WIP buj 2.xlsx"
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
Sheets("calculations").Select
Workbooks.Open Filename:= _
"C:\Users\do\Desktop\desktop\karai data\KARAI 1.xlsx"
Range("A1:A177").Select
Selection.Copy
Windows("WIP buj 2.xlsx").Activate
Sheets("calculations").Select
Range("A1").Select
ActiveSheet.Paste
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("Sheet5").Select
Range("A1:g39").Select
Selection.Copy
wdApp.Selection.PasteExcelTable False, False, True
wd.SaveAs
wd.Close
wdApp.Quit

I believe by adding a simple loop across each column, stopping when the cell in row 1 is empty, you should be able to achieve what you are after.
Refactored code:
Sub test()
Dim wbSrc As Workbook
Dim wbDst As Workbook
Dim wsSrc As Worksheet
Dim wsDst As Worksheet
Dim wsCpy As Worksheet
Dim c As Long
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
wdApp.Visible = True
Set wbDst = Workbooks.Open(Filename:="C:\Users\DO\Desktop\WIP buj 2.xlsx")
Set wsDst = wbDst.Worksheets("calculations")
Set wsCpy = wbDst.Worksheets("Sheet5")
Set wbSrc = Workbooks.Open(Filename:="C:\Users\do\Desktop\desktop\karai data\KARAI 1.xlsx")
Set wsSrc = ActiveSheet ' Would be better to define this explicitly using the sheet name
c = 1
Do While Not IsEmpty(wsSrc.Cells(1, c).Value)
wsSrc.Cells(1, c).Resize(177, 1).Copy wsDst.Range("A1")
'Copy to Word
'Create new document
Set wd = wdApp.Documents.Add
'Copy Excel data
wsCpy.Range("A1:g39").Copy 'Avoid Excel's "Select" whenever possible!
'Paste in Word
wdApp.Selection.PasteExcelTable False, False, True
'Save and close
wd.SaveAs
wd.Close
'Next column
c = c + 1
Loop
wdApp.Quit
End Sub

Related

From a few Excel files to PowerPoint

I'm totally new in VBA programming. However I have to (and want) create macro in Excel file to automatically creating PowerPoint presentation.
I hope that someone will be able to help me or have a similar problem.
Namely - I have 6 columns in the Excel file:
1 - slide number
2 - file access path
3 - file name
4 - sheet name
5 - slide range
6 - slide title
I would like the macro to automatically enter a given file -> sheet -> take the slide's range, copy and paste it as a picture for the presentation and give it the appropriate title and go through the loop to the next line and do the same.
Is anyone able to help me? Below is the code that I managed to write, however, I do not know how to refer to the sheet and the range of the slide from the given cell.
Option Explicit
Sub ExcelRangeToPowerPoint()
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim adr1 As String
Dim shta As Worksheet
Dim wrk As String
Application.DisplayAlerts = False
wrk = ThisWorkbook.Name ' nname
adr1 = Worksheets("Sheet1").Range("B2")
'Copy Range from Excel
' Set rng = ThisWorkbook.ActiveSheet.Range("A1:C12")
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
ThisWorkbook.Activate
Range("A2").Select
'DO While
Do While ActiveCell.Value <> ""
Workbooks.Open Filename:=(ActiveCell.Offset(0, 1) & "\" & ActiveCell.Offset(0, 2)), UpdateLinks:=0, ReadOnly:=True ' to be sure read-only open
' Worksheet Open from D2
'Copy Range from E2
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 11) '11 = ppLayoutTitleOnly
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile + title from F2
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
ActiveWorkbook.Close SaveChanges:=False ' close file and don't save
ActiveCell.Offset(1, 0).Range("A1").Select
Loop
MsgBox ("Ready")
Application.CutCopyMode = False
Application.DisplayAlerts = True
End Sub
You can always refer to some sheet or Workbook creating first variables type Workbook or Worksheets.
If you want to refer a variable to a worksheet/workbook, is pretty easy. Is just a set. Something like:
Dim wb as Workbook
Set wb = ThisWorkbook
Now wb will be referenced to ThisWorkbook Object. With Worksheets is the same. You refer exactly the same way:
Dim ws as Worksheet
Set ws = ActiveSheet
Now ws is referenced to activesheet and you can handle it from ws.
I hope this answered some of your doubts. About your code, the loop part should be something like this:
Dim MyWb As Workbook 'variable for workbook
Dim MyWs As Worksheet 'variable for worksheet
ThisWorkbook.Activate
Range("A2").Select
'DO While
Do While ActiveCell.Value <> ""
ThisWorkook.Activate
Set MyWb = Workbooks.Open(Filename:=(ActiveCell.Offset(0, 1) & "\" & ActiveCell.Offset(0, 2)), UpdateLinks:=0, ReadOnly:=True) ' to be sure read-only open
' Worksheet Open from D2
Set MyWs = MyWb.Worksheets(ActiveCell.Offset(0, 3).Value) 'now MyWs is referenced to the worksheet in column D
'Copy Range from E2
MyWs.Activate
MyWs.Range(ActiveCell.Offset(0, 4).Value).Copy 'we copy the range shown in column E
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 11) '11 = ppLayoutTitleOnly
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile + title from F2
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'after pasting, we go back to active workbook
Application.CutCopyMode = False
MyWb.Activate
MyWb.Close SaveChanges:=False ' close file and don't save
Set MyWs = Nothing
Set MyWb = Nothing
ActiveCell.Offset(1, 0).Select 'we go 1 row down
Loop
I hope you can test it and tell me if it helped you to make thing clear :)
Really Thanks for answer
I had to use "ThisWorkbook.Activate" in a few places.
And now this macro work almost perfect.. it means that the order of creating slides is reversed : 1 is the last and the last is 1..
What is more I'd like to also create Title of each slide from Excel file column F.
Below my VBA code:
Sub VBA_PowerPoint()
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim MyWb As Workbook 'variable for workbook
Dim MyWs As Worksheet 'variable for worksheet
Dim MyRg As Excel.Range ' variable for Range
Application.DisplayAlerts = False
ThisWorkbook.Activate
Range("A2").Select
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
'Do While
ThisWorkbook.Activate
Do While ActiveCell.Value <> ""
ThisWorkbook.Activate
Set MyWb = Workbooks.Open(Filename:=(ActiveCell.Offset(0, 1) & "\" & ActiveCell.Offset(0, 2)), UpdateLinks:=0, ReadOnly:=True) ' to be sure read-only open
' Worksheet Open from D2
ThisWorkbook.Activate
Set MyWs = MyWb.Worksheets(ActiveCell.Offset(0, 3).Value) 'now MyWs is referenced to the worksheet in column D
'Copy Range from E2
' Set MyRg = MyWs.Range(ActiveCell.Offset(0, 4).Value) 'now MyWs is referenced to the worksheet in column E
' MyWs.Range(MyRg).Copy 'we copy the range shown in column E
ThisWorkbook.Activate
MyWs.Range(ActiveCell.Offset(0, 4).Value).Copy
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 11) '11 = ppLayoutTitleOnly
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile + title from F2
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'after pasting, we go back to active workbook
Application.CutCopyMode = False
MyWb.Activate
MyWb.Close SaveChanges:=False ' close file and don't save
Set MyWs = Nothing
Set MyWb = Nothing
ActiveCell.Offset(1, 0).Select 'we go 1 row down
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

How to integrate the excel range into one single table?

I have two ranges in the excel file .
(A79-I84) & (A90-I92)
I am now using the Excel.RANGE.copy. to copy the two tables and paste on the word file .
However , the two ranges become two separate tables and the original excel table format cannot inherit to the new word file .Also , some cells from the word report will be shown in two lines .
In conclusion , the format of the word report will be very messy .
How to integrate the two table into one table with good table format or alignments?
the new table will be generated like this :
(red pen = problems )
My codes:
Sub ExcelRangeToWord()
Dim tbl0 As Excel.RANGE
Dim tbl As Excel.RANGE
Dim tbl2 As Excel.RANGE
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Copy Range from Excel
'Set tbl0 = ThisWorkbook.Worksheets(sheet9.Name).RANGE("A78:I83")
Set tbl = ThisWorkbook.Worksheets(sheet9.Name).RANGE("A78:I83")
Set tbl2 = ThisWorkbook.Worksheets(sheet9.Name).RANGE("A90:I92")
'Create an Instance of MS Word
On Error Resume Next
'Is MS Word already opened?
Set WordApp = GetObject(Class:="Word.Application")
'Clear the error between errors
Err.Clear
'If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(Class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate
'Create a New Document
Set myDoc = WordApp.Documents.Add
'Trigger copy separately for each table + paste for each table
tbl.Copy ' paste range1
myDoc.Paragraphs(1).RANGE.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=True, _
RTF:=False
'before that...
'...go to end of doc and add new paragraph
myDoc.Bookmarks("\EndOfDoc").RANGE.InsertParagraphAfter
tbl2.Copy 'paste range2
'Paste Table into MS Word last paragraph
myDoc.Paragraphs(myDoc.Paragraphs.Count).RANGE.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=True, _
RTF:=False
'Autofit Table so it fits inside Word Document
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
new aftereffect
Try the following. Simply hide rows in between (which ever you don't want to see) and copy as one range to be from "A79:I92" and paste as a picture. Credit here (#sneep) for sub to resize image. Note this will resize all images but could be adapted to target just one.
Option Explicit
Sub ExcelRangeToWord()
Dim tbl0 As Excel.Range
Dim Tbl As Excel.Range
Dim tbl2 As Excel.Range
Dim wordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet2") ' Change e.g. sheet9.Name
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
ws.Rows("84:89").EntireRow.Hidden = True 'ADJUST AS APPROPRIATE
'Copy Range from Excel
'Set tbl0 = ws.RANGE("A78:I83")
Set Tbl = ws.Range("A78:I92")
' Set tbl2 = ws.Range("A90:I92")
'Create an Instance of MS Word
On Error Resume Next
'Is MS Word already opened?
Set wordApp = GetObject(Class:="Word.Application")
'Clear the error between errors
Err.Clear
'If MS Word is not already open then open MS Word
If wordApp Is Nothing Then Set wordApp = CreateObject(Class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
wordApp.Visible = True
wordApp.Activate
'Create a New Document
Set myDoc = wordApp.Documents.Add
'Trigger copy separately for each table + paste for each table
Tbl.CopyPicture Appearance:=xlScreen, Format:=xlPicture
wordApp.Selection.Paste
wordApp.Selection.TypeParagraph
wordApp.Selection.PageSetup.Orientation = wdOrientLandscape
resize_all_images_to_page_width myDoc
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
Sub resize_all_images_to_page_width(myDoc As Document)
'https://blog.qiqitori.com/?p=115
Dim inline_shape As InlineShape
Dim percent As Double
For Each inline_shape In myDoc.InlineShapes
inline_shape.LockAspectRatio = msoFalse
inline_shape.ScaleWidth = 100
inline_shape.ScaleHeight = 100
percent = myDoc.PageSetup.TextColumns.Width / inline_shape.Width
inline_shape.ScaleWidth = percent * 100
inline_shape.ScaleHeight = percent * 100
Next
End Sub

Trying to copy data from several ranges in Excel to MS Word

I'm playing around with this code snippet, which I found on SO.
Sub Test()
Dim objWord As Object
Dim ws As Worksheet
Set ws1 = ThisWorkbook.Sheets("Contact Information1")
Set ws2 = ThisWorkbook.Sheets("Contact Information2")
'Set ws3 = ThisWorkbook.Sheets("Contact Information3")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\rshuell001\Desktop\Final Report.docx" ' change as required
With objWord.ActiveDocument
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
.Bookmarks("BkMark2").Range.Text = ws2.Range("A1:F8").Value
'.Bookmarks("Report3").Range.Text = ws3.Range("A1:F80").Value
End With
Set objWord = Nothing
End Sub
When I look at it, it makes sense. When I run the script, I get an error on this line:
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
The error message is:
Run-type error 13
Type mismatch
1) I'm not sure '.Bookmarks("BkMark1").Range.Text' will do what I want. I think it's more of a standard copy/paste.
2) I want to make sure the table fits in the Word document, so I'm going to need something like the line below, to get it to do what I want.
wd.Tables(1).AutoFitBehavior wdAutoFitWindow
Any ideas on how to make this work?
Thanks!
I came up with the script below. It does what I want.
Sub Export_Table_Word()
'Name of the existing Word doc.
'Const stWordReport As String = "Final Report.docx"
'Word objects.
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim wdbmRange1 As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet1 As Worksheet
Dim rnReport1 As Range
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set WDApp = New Word.Application
'Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set WDDoc = WDApp.Documents.Open("C:\Users\rshuell001\Desktop\Final Report.docx")
'Delete old fields and prepare to replace with new
Dim doc As Document
Dim fld As Field
Set doc = WDDoc
For Each fld In doc.Fields
fld.Select
If fld.Type = 88 Then
fld.Delete
End If
Next
Set wsSheet = wbBook.Worksheets("Contact Information1")
Set rnReport = wsSheet.Range("BkMark1")
Set wdbmRange = WDDoc.Bookmarks("BkMark1").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.
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information2")
Set rnReport = wsSheet.Range("BkMark2")
Set wdbmRange = WDDoc.Bookmarks("BkMark2").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(2).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information3")
Set rnReport = wsSheet.Range("BkMark3")
Set wdbmRange = WDDoc.Bookmarks("BkMark3").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(3).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With WDDoc
.Save
.Close
End With
'Quit Word.
WDApp.Quit
'Null out your variables.
Set fld = Nothing
Set doc = Nothing
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

Paste multiple sheets into a single Word document

I'm trying to copy and paste each worksheet in a workbook onto a new sheet in a single Word document. Unfortunately it is only copying the contents of the first worksheet, though it does seem to be looping through all the worksheets. I thought that inserting a page break would work but it isn't. It also won't let me format it in Word. I want the contents of A1 to have a header style.
This is my code:
Sub ExceltoWord()
Dim ws As Worksheet
Dim Wkbk1 As Workbook
Set Wkbk1 = ActiveWorkbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each ws In Wkbk1.Worksheets
Wkbk1.ActiveSheet.Range("A1:A2").Copy
Dim wdapp As Object
Dim wddoc As Object
Dim Header As Range
'file name & folder path
Dim strdocname As String
On Error Resume Next
'error number 429
Set wdapp = GetObject(, "Word.Application")
If Err.Number = 429 Then
Err.Clear
'create new instance of word application
Set wdapp = CreateObject("Word.Application")
End If
wdapp.Visible = True
'define paths to file
strdocname = "P:\ImportedDescriptions.doc"
If Dir(strdocname) = "" Then
MsgBox "The file" & strdocname & vbCrLf & "was not found " & vbCrLf & "P:\ImportedDescriptions.doc", vbExclamation, "The document does not exist "
Exit Sub
End If
wdapp.Activate
Set wddoc = wdapp.Documents(strdocname)
If wddoc Is Nothing Then Set wddoc = wdapp.Documents.Open(strdocname)
Set Header = Range("A1")
'must activate to be able to paste
wddoc.Activate
wddoc.Range.Paste
Selection.WholeStory
Header.Style = ActiveDocument.Styles("Heading 2")
Selection.InsertBreak Type:=wdPageBreak
Next ws
wddoc.Save
'wdapp.Quit
Set wddoc = Nothing
Set wdapp = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
You are only copying from the active worksheet, which happens to be the first sheet in your case. Instead of:
For Each ws In ActiveWorkbook.Worksheets
ActiveWorkbook.ActiveSheet.Range("A1:A2").Copy
use:
For Each ws In ActiveWorkbook.Worksheets
ws.Range("A1:A2").Copy
This will copy each range in turn.
I think it is losing track of which workbook you started with when you activate Word. Save your workbook to a Workbook variable (i.e. Dim Wkbk1 As Workbook, Set Wkbk1 = ActiveWorkbook) then replace every instance of ActiveWorkbook in your code after that with Wkbk1 (in your For Each loop and every time you want to reference it inside the loop as well).

VBA copy and paste macro != manual copy paste

Im trying to copy and paste a table from excel into a word document.
I can do it manually - highlight the cell, CTRL+C, go to word, CTRL+V. it works fine.
But when I write a macro to do it the cells are twice the height, like the line height in each cell gets changed for some reason. why is it different? I recorded the manual procedure and it is the same function (PasteExcelTable) being called.
Set wordDoc = wordApp.Documents.Open(wordDocPath)
With wordDoc
' cost report
Dim wordRng As Word.Range
Dim xlRng As Excel.Range
Dim sheet As Worksheet
Dim i As Integer
Dim r As String
'Copy the cost report from excel sheet
Set sheet = ActiveWorkbook.Sheets("COST REPORT")
i = sheet.Range("A:A").Find("TOTAL PROJECT COST", Range("A1"), xlValues, xlWhole, xlByColumns, xlNext).row
r = "A11:M" + Trim(Str(i))
Set xlRng = sheet.Range(r)
xlRng.Copy
'Copy and Paste Cost report from Excel
Set wordRng = .Bookmarks("CostReport").Range 'remember original range
If .Bookmarks("CostReport").Range.Information(wdWithInTable) Then
.Bookmarks("CostReport").Range.Tables(1).Delete
End If
.Bookmarks("CostReport").Range.PasteExcelTable False, False, False
.Bookmarks.Add "CostReport", wordRng 'reset range to its original positions
End With
Here is my solution:
With wordDoc
'Paste table from Excel
Set wordRng = .Bookmarks(bookMarkName).range 'remember original range
If .Bookmarks(bookMarkName).range.Information(wdWithInTable) Then
.Bookmarks(bookMarkName).range.Tables(1).Delete
End If
.Bookmarks(bookMarkName).range.PasteExcelTable False, False, False
.Bookmarks.Add bookMarkName, wordRng 'reset range to its original positions
Dim paraFmt As ParagraphFormat
Set paraFmt = .Bookmarks(bookMarkName).range.Tables(1).range.ParagraphFormat
paraFmt.SpaceBefore = 0
paraFmt.SpaceBeforeAuto = False
paraFmt.SpaceAfter = 0
paraFmt.SpaceAfterAuto = False
paraFmt.LineSpacingRule = wdLineSpaceSingle
paraFmt.WidowControl = True
paraFmt.KeepWithNext = False
paraFmt.KeepTogether = False
paraFmt.PageBreakBefore = False
paraFmt.NoLineNumber = False
paraFmt.Hyphenation = True
paraFmt.OutlineLevel = wdOutlineLevelBodyText
paraFmt.CharacterUnitLeftIndent = 0
paraFmt.CharacterUnitRightIndent = 0
paraFmt.CharacterUnitFirstLineIndent = 0
paraFmt.LineUnitBefore = 0
paraFmt.LineUnitAfter = 0
paraFmt.MirrorIndents = False
paraFmt.TextboxTightWrap = wdTightNone
paraFmt.Alignment = wdAlignParagraphLeft
.Bookmarks(bookMarkName).range.Tables(1).AutoFitBehavior (wdAutoFitWindow)
End With
Try this sample piece of code for me please. I tested it From VBA Excel with different table types and it gave me satisfactory results. Please amend it whereever required... for example File Name / Sheet name etc...
Sub Sample()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
FlName = "C:\MyDoc.doc"
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
With oWordDoc
Dim xlRng As Range
Set xlRng = Sheets(1).Range("A1:D10")
xlRng.Copy
.Bookmarks("CostReport").Range.PasteSpecial Link:=False, _
Placement:=wdInLine, DisplayAsIcon:=False
End With
End Sub