I have a workbook full of worksheets I'm trying to copy and paste the contents of into a word document. Right now the code loops through all the worksheets and pastes them into a word document, but on top of each other. I had to change wdDoc.Range(wdDoc.Characters.Count - 1).Paste to wdDoc.Range(wdDoc.Characters.Count - 1).PasteExcelTable False, False, False and I'm not sure if this is the source of the problem; it does seem like a new page is being created, but the contents of the next worksheet just aren't being pasted into it. I'm not getting any error messages. Any advice would be appreciated!
Sub toWord()
Dim ws As Worksheet
Dim fromWB As Variant
Dim wdApp As Object
Dim wdDoc As Object
Dim docName As Variant
Dim rng As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Add
wdDoc.Activate
'Creates InputBox that allows user to enter name to save document as
docName = Application.InputBox(Prompt:="Enter Document Name", Title:="Save Word Document", Type:=2)
wdDoc.SaveAs2 fileName:=docName, FileFormat:=wdFormatDocument 'Saves document under user-provided name
fromWB = Application.GetOpenFilename(FileFilter:="Excel Workbook(*.xlsx),*.xlsx", Title:="Open Merged Data")
If fromWB <> False Then
Set fromWB = Workbooks.Open(fromWB)
ElseIf fromWB = False Then
MsgBox "No File Selected"
GoTo ResetSettings
End If
For Each ws In fromWB.Worksheets
ws.Activate
ws.Range("A1:A2").Select
Selection.Copy
Set wdApp = GetObject(, "Word.Application")
wdApp.Visible = True
wdDoc.Activate
wdDoc.Range.Paste
ws.Activate
If ws.Range("A3").Value <> "" Then
Range("A2").CurrentRegion.Offset(2).Resize(Range("A2").CurrentRegion.Rows.Count - 2).Select
Selection.Columns.AutoFit
Selection.Copy
Set wdApp = GetObject(, "Word.Application")
wdApp.Visible = True
wdDoc.Activate
wdApp.Selection.EndKey Unit:=wdStory
wdApp.Selection.MoveDown Unit:=wdLine, Count:=1
wdApp.Selection.TypeParagraph
wdDoc.Range(wdDoc.Characters.Count - 1).PasteExcelTable False, False, False
wdApp.Selection.Tables(1).Rows.Alignment = wdAlignRowCenter
wdDoc.Range.Collapse Direction:=0
wdDoc.Range(wdDoc.Characters.Count - 1).InsertBreak Type:=7
End If
Next ws
wdDoc.Styles("Normal").NoSpaceBetweenParagraphsOfSameStyle = True
wdDoc.Save
Set wdDoc = Nothing
Set wdApp = Nothing
Set fromWB = Nothing
MsgBox "Imported into Word Document"
ResetSettings:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
Placeholder edit while testing:
Sub asdf()
Dim ws As Worksheet
Const wdStory = 6
Const wdMove = 0
For Each ws In ThisWorkbook.Worksheets
ws.Range("A7").Copy
Set docApp = GetObject(, "Word.Application")
Set doc = docApp.Documents.Open("PATH OF FILE")
docApp.Selection.EndKey wdStory
docApp.Selection.PasteAndFormat wdPasteDefault
Next ws
End Sub
Here's the code I got to work:
Sub toWord()
Dim ws As Worksheet
Dim fromWB As Variant
Dim wdApp As Object
Dim wdDoc As Object
Dim docName As Variant
Dim rng As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Add
wdDoc.Activate
'Creates InputBox that allows user to enter name to save document as
docName = Application.InputBox(Prompt:="Enter Document Name", Title:="Save Word Document", Type:=2)
wdDoc.SaveAs2 fileName:=docName, FileFormat:=wdFormatDocument 'Saves document under user-provided name
fromWB = Application.GetOpenFilename(FileFilter:="Excel Workbook(*.xlsx),*.xlsx", Title:="Open Merged Data")
If fromWB <> False Then
Set fromWB = Workbooks.Open(fromWB)
ElseIf fromWB = False Then
MsgBox "No File Selected"
GoTo ResetSettings
End If
For Each ws In fromWB.Worksheets
ws.Activate
ws.Range("A1:A2").Select
Selection.Copy
Set wdApp = GetObject(, "Word.Application")
wdApp.Visible = True
wdDoc.Activate
wdDoc.Range(wdDoc.Characters.Count - 1).Paste
ws.Activate
If ws.Range("A4").Value <> "" Then
Application.Intersect(ws.UsedRange, ws.Cells.Resize(ws.Rows.Count - 2).Offset(2)).Select
Selection.Columns.AutoFit
Selection.Copy
Set wdApp = GetObject(, "Word.Application")
wdApp.Visible = True
wdDoc.Activate
wdApp.Selection.EndKey Unit:=wdStory
wdApp.Selection.MoveDown Unit:=wdLine, Count:=1
wdApp.Selection.TypeParagraph
wdDoc.Range(wdDoc.Characters.Count - 1).PasteExcelTable False, False, False
wdApp.Selection.Tables(1).Rows.Alignment = wdAlignRowCenter
wdApp.Selection.Collapse Direction:=0
wdDoc.Range(wdDoc.Characters.Count - 1).InsertBreak Type:=7
Else
wdDoc.Range(wdDoc.Characters.Count - 1).InsertBreak Type:=7
End If
Next ws
wdDoc.Styles("No Spacing").NoSpaceBetweenParagraphsOfSameStyle = True
wdDoc.Save
Set wdDoc = Nothing
Set wdApp = Nothing
Set fromWB = Nothing
MsgBox "Imported into Word Document"
ResetSettings:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
Related
I want to insert the Excel file at the seartain BOOkmark in the Word doc without opening Excel, automatically inserted when the Word doc opens.
1.I'm thinking to make a pop up window with a open file dialog bottom firstly. And my code is following:(but it only work in excel VBA doesn't work in word VBA how should I change the code so that I can do it in word??? )
Sub openfile()
Dim intChoice As Integer
Dim strPath As String
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
End If
End Sub
Then I made a copy and paste bottom the code is as follows:(It also only work when l code it in excel how to change to word vba?)
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
For Each ws In ActiveWorkbook.Worksheets
ws.UsedRange.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not ws.Name = Worksheets(Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next ws
Set ws = Nothing
Application.StatusBar = "Cleaning up..."
With wdApp.ActiveWindow
If .View.SplitSpecial = wdPaneNone Then
.ActivePane.View.Type = wdNormalView
Else
.View.Type = wdNormalView
End If
End With
Set wdDoc = Nothing
wdApp.Visible = True
Set wdApp = Nothing
Application.StatusBar = False
End Sub
This should get you started. Place the code below in your Word document in the 'ThisDocument' module.
Add Excel reference to your Word VBA. In the VBA editor go to Tools and then References. Check the box next to Microsoft Excel 14.0 Object Library.
Private Sub Document_Open()
Dim intChoice As Integer
Dim strPath As String
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
End If
CopyWorksheetsToWord (strPath)
End Sub
Function CopyWorksheetsToWord(filePath As String)
Dim exApp As Excel.Application
Dim exWbk As Excel.Workbook
Dim exWks As Excel.Worksheet
Dim wdDoc As Word.Document
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdDoc = ActiveDocument
Set exApp = New Excel.Application
exApp.Visible = False
Set exWbk = exApp.Workbooks.Open(filePath)
For Each exWks In exWbk.Worksheets
exWks.UsedRange.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
exApp.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not exWks.Name = exWbk.Worksheets(exWbk.Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next exWks
Application.StatusBar = "Cleaning up..."
Set exWks = Nothing
exWbk.Close
Set exWbk = Nothing
Set exApp = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
End Function
Save file as macro-enabled file (.docm)
Close word file
Open word file and the code will run. First thing you'll see is a file open box to select the Excel file.
Tested code but there is no error checking.
Update per comment
Bookmarks can be located by name using the following syntax: wdDoc.Bookmarks("Bookmark2").Range
In this case I inserted a bookmark and labeled it Bookmark2
Updated Function Code:
Function CopyWorksheetsToWord(filePath As String)
Dim exApp As Excel.Application
Dim exWbk As Excel.Workbook
Dim exWks As Excel.Worksheet
Dim wdDoc As Word.Document
Dim bmRange As Range
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdDoc = ActiveDocument
Set exApp = New Excel.Application
exApp.Visible = False
Set exWbk = exApp.Workbooks.Open(filePath)
For Each exWks In exWbk.Worksheets
exWks.UsedRange.Copy
Set bmRange = wdDoc.Bookmarks("Bookmark2").Range
bmRange.Paste
exApp.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not exWks.Name = exWbk.Worksheets(exWbk.Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next exWks
Application.StatusBar = "Cleaning up..."
Set exWks = Nothing
exWbk.Close
Set exWbk = Nothing
Set exApp = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
End Function
Since your looping through sheets you'll probably need to play with formatting and how your stacking each section in the document but this should get you going.
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
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
I keep getting the 462 error the second or third time I run this loop. I don't think I have any objects that are floating but maybe I missed something, I am kind of new at this. This macro is taking all the charts from Excel, pasting them into Word as pictures, resizing them, saving the document and closing it. The For loop has formatting for the chart to be pasted as a normal picture and the text below it to be caption so I can create a figure table easily.
The error takes place in the .Height = InchesToPoints(6.1) line.
Private Sub ChartstoWord_Click()
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim cname, wordname, restage, pNumber, wfile As String
Dim n As Integer
Dim i As Long
Application.ScreenUpdating = False
If wordfile.Value = "" Then
MsgBox "Please enter a word file name", vbOKOnly
Exit Sub
End If
wfile = CurveDirectoryBox & "\" & wordfile.Value & ".docx"
wordname = UCase(dataname.Value)
'if word file doesn't exist then it makes the word file for you
If Dir(wfile) = "" Then
Set WDApp = CreateObject("Word.application")
WDApp.Visible = True
Set WDDoc = WDApp.Documents.Add
WDApp.Visible = True
With WDDoc
.SaveAs wfile
.Close
End With
Set WDDoc = Nothing
WDApp.Quit
Set WDApp = Nothing
End If
' Create new instance of Word and open filename provided if file exists
Set WDApp = CreateObject("Word.application")
WDApp.Visible = True
WDApp.Documents.Open wfile
WDApp.Visible = True
Set WDDoc = WDApp.ActiveDocument
With WDDoc
.Range(start:=.Range.End - 1, End:=.Range.End - 1).Select
.PageSetup.Orientation = wdOrientLandscape
End With
For n = 1 To Charts.Count
Charts(n).Select
cname = ActiveChart.ChartTitle.Characters.Text
ActiveChart.CopyPicture _
Appearance:=xlScreen, Format:=xlPicture
' Paste chart at end of current document
WDApp.Visible = True
With WDApp
.Selection.Style = WDApp.ActiveDocument.Styles("Normal")
.Selection.Font.Size = 12
.Selection.Font.Bold = True
.Selection.PasteSpecial Link:=False, Placement:=wdInLine, DisplayAsIcon:=False, DataType:=wdPasteEnhancedMetafile
.Selection.TypeParagraph
.Selection.Style = WDApp.ActiveDocument.Styles("Caption")
.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Selection.Font.Size = 12
.Selection.Font.Bold = False
.Selection.TypeText (wordname + " " + cname)
.Selection.TypeParagraph
End With
Next n
'resize all pictures
WDApp.Visible = True
With WDApp
With WDDoc
For i = 1 To WDApp.ActiveDocument.InlineShapes.Count
With WDApp.ActiveDocument.InlineShapes(i)
'.Width = InchesToPoints(7.9)
.Height = InchesToPoints(6.1)
End With
Next i
End With
End With
WDDoc.Save
WDDoc.Close
Set WDDoc = Nothing
WDApp.Quit
Set WDApp = Nothing
Worksheets("Control").Activate
Range("A1").Select
Application.ScreenUpdating = True
End Sub
I was able to solve the problem, ended up being that the command InchesToPoints is a word command and needs the wdapp in front of it. Thanks for all the suggestions, I also cleaned up a code a bit after all your receommendations.
Private Sub ChartstoWord_Click()
Dim WDApp As Word.Application
Dim cname, wordname, restage, pNumber, wfile As String
Dim n As Integer
Dim i, h As Long
Application.ScreenUpdating = False
If wordfile.Value = "" Then
MsgBox "Please enter a word file name", vbOKOnly
Exit Sub
End If
wfile = CurveDirectoryBox & "\" & wordfile.Value & ".docx"
wordname = UCase(dataname.Value)
'if word file doesn't exist then it makes the word file for you
If Dir(wfile) = "" Then
Set WDApp = CreateObject("Word.application")
WDApp.Visible = True
WDApp.Documents.Add
WDApp.ActiveDocument.SaveAs wfile
WDApp.ActiveDocument.Close
WDApp.Quit
Set WDApp = Nothing
End If
' Create new instance of Word and open filename provided if file exists, checks to see if file is open or not already
If IsFileOpen(wfile) = False Then
Set WDApp = CreateObject("Word.application")
WDApp.Visible = True
WDApp.Documents.Open wfile
End If
If IsFileOpen(wfile) = True Then
Set WDApp = GetObject(wfile).Application
WDApp.Visible = True
End If
'moves cursor in word to the end of the document and change page to landscape
WDApp.ActiveDocument.Range(start:=WDApp.ActiveDocument.Range.End - 1, End:=WDApp.ActiveDocument.Range.End - 1).Select
WDApp.ActiveDocument.PageSetup.Orientation = wdOrientLandscape
'loops through all charts and pastes them in word
For n = 1 To Charts.Count
Charts(n).Select
cname = ActiveChart.ChartTitle.Characters.Text
ActiveChart.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WDApp.Visible = True
WDApp.Selection.Style = WDApp.ActiveDocument.Styles("Normal")
WDApp.Selection.Font.Size = 12
WDApp.Selection.Font.Bold = True
WDApp.Selection.PasteSpecial Link:=False, Placement:=wdInLine, DisplayAsIcon:=False, DataType:=wdPasteEnhancedMetafile
WDApp.Selection.TypeParagraph
WDApp.Selection.Style = WDApp.ActiveDocument.Styles("Caption")
WDApp.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
WDApp.Selection.Font.Size = 12
WDApp.Selection.Font.Bold = False
WDApp.Selection.TypeText (wordname + " " + cname)
WDApp.Selection.TypeParagraph
Next n
'resize all pictures
WDApp.Visible = True
For i = 1 To WDApp.ActiveDocument.InlineShapes.Count
WDApp.ActiveDocument.InlineShapes(i).Select
WDApp.ActiveDocument.InlineShapes(i).Height = WDApp.InchesToPoints(6.1)
Next i
WDApp.ActiveDocument.SaveAs wfile
WDApp.ActiveDocument.Close
WDApp.Quit
Set WDApp = Nothing
Worksheets("Control").Activate
Range("A1").Select
Application.ScreenUpdating = True
End Sub
Definitly too much With, and not even used, so here is a version of your resize that should be cleaner but not sure that it'll be enough, give it a try
Too many WDApp.Visible = True also, only one will be enough but as you close it after, you should even set it to False!
'resize all pictures
For i = 1 To WDDoc.InlineShapes.Count
With WDDoc.InlineShapes(i)
'.Width = InchesToPoints(7.9)
.Height = InchesToPoints(6.1)
End With
Next i
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