I am developing a macro that transfers a range of cells from excel to word bookmark. The problem I am having is that not the whole of the range I selected is transfered. Not sure if there is a limit to how big the range can be? Also want the transfered content to autofit to the word documents margins?
The code I have so far is:
'Name of the existing Word doc.
Const stWordReport As String = "Exporting a Table to a Word Document 2.docx"
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Dim Table1 As Range
Dim coluna As Integer
coluna = Worksheets("Planilha1").Cells(1, Worksheets("Planilha1").Columns.Count).End(xlToLeft).Column
Table1 = Worksheets("Planilha1").Range(Cells(4, 4), Cells(16, coluna))
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")
'Initialize the Word objects.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").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
.PasteSpecial Link:=False, _
DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, _
DisplayAsIcon:=False
End With
'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
I expect the content on the word document to have the same formatting as the excel one and to be fitted to the page.
Word's maximum column count is 63; there is no set row limit. In any event, since you are pasting what you've copied as a picture, the table limits aren't relevant. I suspect the real issue is with how you're determining coluna. Try:
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")
coluna = wsSheet.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Column
Table1 = wsSheet.Range(Cells(4, 4), Cells(16, coluna))
Related
I have a series of ranges in Excel.
Example:
table key
table range
table6
A4:G14
table7
A15:G20
table8
A21:E30
and so on.
How can I search a Word document for the names in column 1 and paste the ranges in the second column?
This is the segment of the code I have
For Each cell In rng "rng is the range of the table key column"
If cell.Value = "" Then Exit For
With wdDoc.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = wdFindContinue
.Text = cell.Value
.Replacement.Text = Range(cell.Offset(0, 1))
.Execute Replace:=wdReplaceAll
End With
Next
I get an error in the replacement.text line but I don't know how to replace it with a range.
I also tried the code below to copy and paste the ranges in the table but I get an object defined error at the pasteexceltable line:
Set appWd = CreateObject("Word.Application")
set wdFind = appWd.Selection.Find
For Each cell In rng
If cell.Value = "" Then Exit For
ClipT = " "
Range(cell.Offset(0, 1)).Copy
wdFind.Text = cell.Value
wdFind.Replacement.Text = ""
wdFind.Forward = True
wdFind.Wrap = wdFindContinue
wdFind.Execute
Call CheckClipBrd 'This function checks if the clipboard is empty'
Range(cell.Offset(0, 1)).Copy
ActiveWindow.Selection.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=True
CutCopyMode = False
If, for example, your Word template contains the relevant tables and each is bookmarked with the same name as the table names in Excel, then, provided each Word table:
• has both a header row and an empty data row; and
• the same number of columns as your Excel data,
you could use code like:
Sub ExportToWord()
' Note: A reference to the Microsoft Word # Object Library is required,
' set via Tools|References in the Excel VBE.
Dim WdApp As New Word.Application, WdDoc As Word.Document
Dim XlSht As Excel.Worksheet, XlTbl As Excel.ListObject
Set XlSht = ThisWorkbook.Worksheets("Sheet1")
With WdApp
Set WdDoc = .Documents.Add(Template:="full name & path to template")
For Each XlTbl In XlSht.ListObjects
XlTbl.DataBodyRange.Copy
With WdDoc
If .Bookmarks.Exists(XlTbl.Name) Then
With .Bookmarks.Exists(XlTbl.Name)
.Range.PasteAppendTable
.Rows(2).Delete
End With
End If
End With
Next
End With
End Sub
The reason for the Word table initially having an empty data row is so that the paste doesn't take on the formatting of the header row.
If you really, really don't want to use bookmarks, you would need another way of correlating the Word tables and Excel data (e.g. via Find for an identifying string [such as the Excel table's name] in Word, or by the Word table index # [which might be retrieved from the Excel table's name]).
For example, if the Excel table's name is in the Word table's second row:
Sub ExportToWord()
' Note: A reference to the Microsoft Word # Object Library is required,
' set via Tools|References in the Excel VBE.
Dim WdApp As New Word.Application, WdDoc As Word.Document
Dim XlSht As Excel.Worksheet, XlTbl As Excel.ListObject
Set XlSht = ThisWorkbook.Worksheets("Sheet1")
With WdApp
Set WdDoc = .Documents.Add(Template:="full name & path to template")
For Each XlTbl In XlSht.ListObjects
XlTbl.DataBodyRange.Copy
With WdDoc
With .Range.
With .Find
.Text = XlTbl.Name
.MatchWildcards = True
.Execute
End With
If .Find.Found = True Then
With .Tables(1)
.Range.PasteAppendTable
.Rows(2).Delete
End With
End If
End With
End With
Next
End With
End Sub
or, if the the Word table's index # corresponds with the Excel table's name:
Sub ExportToWord()
' Note: A reference to the Microsoft Word # Object Library is required,
' set via Tools|References in the Excel VBE.
Dim WdApp As New Word.Application, WdDoc As Word.Document
Dim XlSht As Excel.Worksheet, XlTbl As Excel.ListObject
Set XlSht = ThisWorkbook.Worksheets("Sheet1")
With WdApp
Set WdDoc = .Documents.Add(Template:="full name & path to template")
For Each XlTbl In XlSht.ListObjects
XlTbl.DataBodyRange.Copy
With WdDoc
With .Tables(Replace(XlTbl.Name, "Table", ""))
.Range.PasteAppendTable
.Rows(2).Delete
End With
End If
End With
Next
End With
End Sub
Data dynamically populating from drop-down list correctly; however, how may I get the Word document to close properly in between each entry?
Problem:
The Word document doesn't close properly in between each new entry in the Excel dynamic drop-down list.
What is occurring:
The loop is executing over each hospital; however, Word isn't closing in between each new entity. Result is that all the addresses and tables are inserting without interruption.
What should occur:
Each hospital with it's own unique data in a new Word document (attached, the Excel sheet "Table" has a drop-down in call B2 that autopopulates the table 1 and the hospital's address; the Word document has bookmarks to insert this data).
In advance, thank you very much for your expertise. I have tried various commands to close the active document in Word (not shown) but then cannot get Word to open up again with the template. Realize there is likely a simple solution to incorporate into the existing code.
Regards,
Karen
Sub MMISPMT()
Worksheets("table").Activate
'Declare variables
Dim WordApp As Object
Dim WordDoc As Object
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range
ActiveWindow.View = xlNormalView
'Set variables
'Which cell has data validation
Set dvCell = Worksheets("Table").Range("B2") 'this is a drop-down box of entity name values that
populates address info and table 1 in Word document
'Determine where validation comes from
Set inputRange = Evaluate(dvCell.Validation.Formula1)
Set WordApp = New Word.Application ' based on the template ref'd in WordDoc
'Word template to be used
Set WordDoc = WordApp.Documents.Add(Template:="C:\<pathway>\letter.docx", NewTemplate:=False,
DocumentType:=0)
'Begin loop
Application.ScreenUpdating = False
For Each c In inputRange
dvCell = c.Value
MsgBox dvCell
Debug.Print dvCell
Dim table1 As Range
Dim HosName As Range
Dim address1 As Range
Dim city As Range
Dim zip As Range
'Declare variables
Set table1 = Range("a10:g15")
Set HosName = Range("b2")
Set address1 = Range("ad5")
Set city = Range("ad6")
Set zip = Range("ad7")
HosName.Select
Selection.Copy
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("HosName").Select
Set objSelection = WordApp.Selection
objSelection.PasteSpecial DataType:=wdPasteText
address1.Select
Selection.Copy
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("address1").Select
Set objSelection = WordApp.Selection
objSelection.PasteSpecial DataType:=wdPasteText
city.Select
Selection.Copy
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("city").Select
Set objSelection = WordApp.Selection
objSelection.PasteSpecial DataType:=wdPasteText
zip.Select
Selection.Copy
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("zip").Select
Set objSelection = WordApp.Selection
objSelection.PasteSpecial DataType:=wdPasteText
table1.Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("table1").Select
Set objSelection = WordApp.Selection
objSelection.Paste
'Generate the Word template per hospital with data
WordApp.ActiveDocument.SaveAs2 Filename:="C:\<pathway>\" & HosName & " " & Format((Year(Now() + 1)
Mod 100), "20##") & _
Format((Month(Now() + 1) Mod 100), "0#") & _
Format((Day(Now()) Mod 100), "0#") & "-report.docx", _
FileFormat:=wdFormatXMLDocument
Next c
Application.ScreenUpdating = True
End Sub
You need to open the template at the top of the loop, then save and close the document at the bottom of the loop.
Also you can tidy up your code by factoring the copy/paste into a separate method.
Sub MMISPMT()
Dim WordApp As Object
Dim WordDoc As Object
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range, wsTable As Worksheet
Set wsTable = Worksheets("Table")
Set dvCell = Worksheets("Table").Range("B2")
Set inputRange = Evaluate(dvCell.Validation.Formula1)
Set WordApp = New Word.Application ' based on the template ref'd in WordDoc
For Each c In inputRange.Cells
Set WordDoc = WordApp.Documents.Add(Template:="C:\<pathway>\letter.docx", _
NewTemplate:=False, DocumentType:=0)
dvCell = c.Value
CopyToBookmark wsTable.Range("B2"), WordDoc, "HosName"
CopyToBookmark wsTable.Range("AD5"), WordDoc, "address1"
CopyToBookmark wsTable.Range("AD6"), WordDoc, "city"
CopyToBookmark wsTable.Range("AD7"), WordDoc, "zip"
CopyToBookmark wsTable.Range("A10:G15"), WordDoc, "table1", False
WordDoc.SaveAs2 Filename:="C:\<pathway>\" & HosName & " " & _
Format((Year(Now() + 1) Mod 100), "20##") & _
Format((Month(Now() + 1) Mod 100), "0#") & _
Format((Day(Now()) Mod 100), "0#") & "-report.docx", _
FileFormat:=wdFormatXMLDocument
WordDoc.Close
Next c
End Sub
'transfer/copy data from a Range into a named bookmark in doc
' either directly as text or copy/paste as table
Sub CopyToBookmark(rng As Range, doc As Word.document, bmk As String, _
Optional AsValue As Boolean = True)
If AsValue Then
doc.bookmarks(bmk).Range.Text = rng.Value
Else
rng.Copy
doc.bookmarks(bmk).Range.Paste
End If
End Sub
I have a code that copies the page range of a document, creates a new sheet and paste the data there. However, it is not matching the format of the word doc being copied. See code below.
I tried changing selection.copy to selection.copyFormat, but it is simply copying the actual VBA code, and pasting it in the word document.
Sub selectpages()
Dim rgePages As Range
ThisDocument.Activate
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=196
Set rgePages = Selection.Range
Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=207
rgePages.End = Selection.Bookmarks("\Page").Range.End
rgePages.Select
Selection.Copy
Set objNewDoc = Documents.Add
Selection.PasteAndFormat (wdFormatPlainText)
objNewDoc.SaveAs FileName:="C:\Users\GP8535\Desktop\Word Doc" & "\" & "SB 59_test" & ".docx"
objNewDoc.Close
End Sub
There is no need to activate or select anything. Try:
Sub CopyContent()
Dim Rng As Range, RngTmp As Range, wdDoc As Document
With ThisDocument
Set Rng = .Range.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=196)
Set RngTmp = .Range.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=207)
Set RngTmp = RngTmp.GoTo(What:=wdGoToBookmark, Name:="\Page")
Rng.End = RngTmp.End: Set RngTmp = Nothing
End With
Set wdDoc = Documents.Add
With wdDoc
Rng.Copy
.Range.Characters.Last.PasteAndFormat Type:=wdFormatOriginalFormatting
.SaveAs FileName:="C:\Users\GP8535\Desktop\Word Doc\SB 59_test.docx"
.Close
End With
Set Rng = Nothing
End Sub
I'm trying to copy a content from excel into a bookmark in MS word. But I'm getting run time error 424. Kindly help me with it. I'm very new to Visual basics and programming as well. I have attached my code.
Thanks
Sub WordDoc()
Dim wrdApp As Object
Dim Number As String
Dim wrdDoc As Object
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("H:\IP Automation\createDoc.docx")
Number = Worksheets("Sheet1").Range("A2")
Call InsBookmark(ID, Number)
End Sub
Sub InsBookmark(strBMName, strVariable)
If strVariable <> "" Then
If ActiveDocument.Bookmarks.Exists(ID) Then
ActiveDocument.Bookmarks(ID).Select
Selection.Delete
Selection.InsertAfter (strVariable)
End If
End If
End Sub
You shouldn't seperate this into two subs, as the word doc will not persist across them so "ActiveDocument" wont work. just copy the code from the second sub into the first and replace ActiveDocument with wrdDoc
This should work for you. Give it a go and see how you get along.
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 wdbmRange As Word.Range
'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("PwC Contact Information")
Set rnReport = wsSheet.Range("Table1")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").Range
Dim tbl As Table
For Each tbl In wdDoc.Tables
tbl.Delete
Next tbl
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'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
'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
My issue is after I have imported a table from Microsoft Word into Excel by creating an OLEObject, it won't let me copy and paste the table into excel. It continually keeps pasting whatever was last copied on my clipboard into the first cell. Currently my code asks the user for the file name, opens that file as an OLEObject in the active excel sheet, and then pastes the incorrect information into cell A1. It's not copying and pasting what's inside the Word OLEObject.
Sub Macro1()
Dim FName As String, FD As FileDialog
Dim ExR As Range
Set FD = Application.FileDialog(msoFileDialogOpen)
FD.Show
If FD.SelectedItems.Count <> 0 Then
FName = FD.SelectedItems(1)
Else
Exit Sub
End If
ActiveSheet.OLEObjects.Add(fileName:=FName, Link:=False, DisplayAsIcon:=False).Select
Selection.Verb Verb:=xlPrimary
Range("A1").Select
ActiveSheet.Paste
End Sub
Thank you!
From Word to Excel, should be something like this.
Sub ImportFromWord()
'Activate Word Object Library
'Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("word.application") ' Open Word session
WordApp.Visible = False 'keep word invisible
Set WordDoc = WordApp.Documents.Open("C:\Users\your_path_here_\WordFile.docx") ' open Word file
'copy third row of first Word table
WordDoc.Tables(1).Rows(3).Range.Copy
'paste in Excel
Range("A1").PasteSpecial xlPasteValues
WordDoc.Close 'close Word doc
WordApp.Quit ' close Word
End Sub
Or this.
Sub GetTables()
FName = Application _
.GetOpenFilename("Word Files (*.doc), *.doc")
Set WordObject = GetObject(FName)
First = True
RowCount = 2
For Each Tble In WordObject.tables
For i = 1 To 22
If First = True Then
Data = Tble.Rows(i).Cells(1).Range
'Remove cell markers
Cells(1, i) = Left(Data, Len(Data) - 2)
End If
Data = Tble.Rows(i).Cells(2).Range.Text
'Remove cell markers
Cells(RowCount, i) = Left(Data, Len(Data) - 2)
Next i
RowCount = RowCount + 1
First = False
Next Tble
WordObject.Close savechanges = False
End Sub
Using the code from the link How to preserve source formatting while copying data from word table to excel sheet using VB macro? , I've only been able to get the code to work when the macro pastes my Word table in a whole new separate workbook. When clicking a command button that's within the excel workbook that I want to import the Word table to, the table never pastes into the sheet called "Scraping Sheets" I've messed around with the code, but the closest thing I could get was placing the entire table into one cell with all formatting lost.
Private Sub CommandButton22_Click()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim tbl As Object
FlName = Application.GetOpenFilename("Word files (*.Doc*),*.Doc*", , _
On Error Resume Next
Set oWordApp = GetObject(, "Word.Applicaton")
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)
Set tbl = oWordDoc.Tables(1)
Dim wb As Workbook, ws As Worksheet
Set wb = Workbooks.Open(""C:\Users\xxxx\Desktop\292 Int'l_Weekly_Win_Loss_YYYY MM DD TEMPLATE.xlsm"")
Set ws = wb.Sheets("Scraping Sheet")
tbl.Range.Copy
ws.Range("A1").Activate
ws.Paste
MsgBox "Successfully Added File!"
End Sub