I'm trying to open a Word Document and copy the whole table inside it and then paste it into another already-open document after a specific heading/bookmark (that I have bookmarked in the document). Then finally prompt the user to save the document with the newly pasted table.
Examples seen online are Excel-to-Word or Word-to-Excel; I need Word-to-Word.
I'm able to pull up the first document (I think it successfully copies it, too--I haven't tested it), but when it activates the second document, it stops and gives an error that it doesn't have an object assigned.
The debugger highlights Set WrdRng = Active.Bookmarks("AppendixA").Range.
Sub TEST()
'
' Declare Table Document Var as Object
Dim tb As Object
Dim bk As Bookmark
Dim WrdRng As Range
'
'
'Set up Word Application
Set tb = CreateObject("Word.Application")
tb.Visible = True
'Opens Pre-Saved Document & activates it to use
tb.Documents.Open "C:\ Desktop\Table.dotm"
tb.Activate
Selection.WholeStory
'ActiveDocument.Tables(1).Select
Selection.Font.Name = "Calibri"
Selection.Copy
'Activate Rolling Trend Report Document and Paste
Windows("TEST - Compatibility Mode").Activate
' where the error occurs and the debugger highlights
Set WrdRng = Active.Bookmarks("AppendixA").Range
'Paste to Bookmark
With WrdRng
Selection.InsertAfter
End With
'Save Completed Report to Desktop
ChangeFileOpenDirectory "C: \Desktop\"
ActiveDocument.SaveAs2 FileName:="TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
'
'
'
End Sub
Your code is failing because Set WrdRng = Active.Bookmarks("AppendixA").Range should be Set WrdRng = ActiveDocument.Bookmarks("AppendixA").Range
However, your code is badly written, will also fail in other places and will create an extra instance of Word.
The code below is to run from Word
Sub TEST()
'store a pointer to the document you wnat to insert table into
'assumed to be currently active document
Dim targetDoc As Document
Set targetDoc = ActiveDocument
'Open Pre-Saved Document
Dim tblDoc As Document
Set tblDoc = Documents.Open("C:\ Desktop\Table.dotm")
Dim source As Range
Set source = tblDoc.Content
'exclude the paragraph that comes after the table
source.MoveEnd Unit:=wdCharacter, Count:=-1
source.Font.Name = "Calibri"
Dim appxA As Range
Set appxA = targetDoc.Bookmarks("AppendixA").Range
appxA.Collapse wdCollapseEnd
'transfer the text and close the source document
appxA.FormattedText = source.FormattedText
tblDoc.Close wdDoNotSaveChanges
'it is necessary to pass the full file path to the SaveAs command
ActiveDocument.SaveAs2 FileName:="C: \Desktop\TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
End Sub
Related
I am currently working on a project that have one word template embedded in one excel template.
A button in excel was created for opening the embedded word template, exporting the data from excel and puting them into word by using bookmarks in word template. The issue is that word report can be generated only once, because the text will be insert into the original bookmark rather than overwrite the previous data.
I'm trying to export a named field from excel(CoverPageRCA) and copy it into an embedded word template using a bookmark (bkmtable1_1).
I get:
run-time error 13 Type mismatch
that occurs at the following line:
Set bkMark = ActiveDocument.Bookmarks(bookmarkname).Range
I searched the web and spent almost 24 hrs on it. Can anybody please suggest a solution?
Option Explicit
Dim WD As New Word.Application
Dim RCAcell1 As Range
Sub CreateRCAReports1()
Dim wordDoc As Word.Document
Dim oleObj As oleObject
Dim WordApp As Word.Application
WD.Visible = True
Set oleObj = ActiveWorkbook.Sheets("CoverPageRCA").OLEObjects(1)
oleObj.Verb xlVerbPrimary
Set WordApp = oleObj.Object.Application
With WordApp
.Visible = True
.Activate
Set wordDoc = .Documents(1)
End With
'-------------------------------------------------------
ThisWorkbook.Sheets("CoverPageRCA").Activate
ActiveSheet.Range("B2").Select
Set RCAcell1 = ActiveSheet.Range(ActiveCell, ActiveCell.End(xlDown))
'go to each bookmark and type in details
CopyCell1 "bkmtable1_1", 1
Set WD = Nothing
End Sub
'----------------------------------------------------------
Sub CopyCell1(bookmarkname As String, RowOffset As Integer)
Dim bkMark As Range
'clear content on each bookmark and add new bookmarK
Set bkMark = ActiveDocument.Bookmarks(bookmarkname).Range
bkMark.Select
bkMark.Text = "dsfsf"
ActiveDocument.Bookmarks.Add bookmarkname, bkMark
'copy each cell to relevant Word bookmark
WD.Selection.GoTo What:=wdGoToBookmark, Name:=bookmarkname
WD.Selection.TypeText RCAcell1(RowOffset, 1).Value
End Sub
Looking at the code, the issue is on declaration of bkMark:
Dim bkMark As Range
The range object exists on both Excel and Word (different objects), and as the code above runs on excel, it will declare bkMark as an Excel Range object, not a Word Range object.
But the range returned on the line below is a Word range, causing the type mismatch error.:
Set bkMark = ActiveDocument.Bookmarks(bookmarkname).Range
To fix this issue, you must declare bkMark as a Word range,:
Dim bkMark As Word.Range
I am copying Excel cell contents to a bookmark on a Form Edit restricted (2010) Word document but it will only paste if the protection is turned off.
The code I currently have to turn the protection on again afterwards errors. What is the correct code?
Is there a way to make this copy and paste without turning off the protection?
Second problem is that when the text is pasted to the bookmark the font is Red (if manually entered on the document it is in black). The Word default is set as black (I reset the default for good measure). Typing in a new document is in black, however, when Word opens the font icon shows red even though checking the default it is still shows black. Can I define the font colour in the VBA to override this issue until is is resolved or can you suggest a way to fix the Word default?
Sub Arzbericht_Brandstetter()
' x - Defined Cell Names - ARTBrandPATH , ARTBrandDOC
' Excel Word Bookmark
' x - Defined Cell Names - ARZKrankenhaus Text65
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Dim Wd As Object
Dim wdDoc As Object
Dim BrandstetterDoc As Object
Dim BrandstetterPath As String
Dim f As Boolean
BrandstetterPath = ActiveSheet.Range("ARTBrandPATH").Value & ActiveSheet.Range("ARTBrandDOC").Value & ".doc" ' x
' On Error Resume Next
Set BrandstetterDoc = GetObject(BrandstetterPath)
If BrandstetterDoc Is Nothing Then
Set Wd = GetObject(, "Word.Application")
If Wd Is Nothing Then
Set Wd = CreateObject("Word.Application")
If Wd Is Nothing Then
MsgBox "Failed to start Word!", vbCritical
Exit Sub
End If
f = True
End If
Set BrandstetterDoc = Wd.Documents.Open(BrandstetterPath)
If BrandstetterDoc Is Nothing Then
MsgBox "Failed to open Brandstetter Document!" & vbNewLine & _
" Check File Directory is correct", vbCritical
If f Then
Wd.Quit
End If
Exit Sub
End If
Wd.Visible = True
Else
With BrandstetterDoc.Parent
.Visible = True
.Activate
' Turn Protection OFF
With ActiveDocument
.Unprotect "xxxxx"
.Protect wdAllowOnlyRevisions, , Password:="xxxxx"
End With
BrandstetterDoc.Bookmarks("Text65").Range.Text = ws.Range("ARZKrankenhaus").Value
' Turn Protection ON (Restricted Editing)
' ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End With
End If
End Sub
Because its a Formfield and not just a bookmark I changing the code as below which resolved the strange red font issue. I can now copy to the document protected.
From
BrandstetterDoc.Bookmarks("Text65").Range.Text = ws.Range("ARZKrankenhaus").Value
To
ActiveDocument.FormFields("Text65").Result = ws.Range("ARZKrankenhaus").Value
I'm using Excel 2010 with an embedded Word Document. The Word document is basically a communication template with some formatting (bold / underline / hyperlinks).
Process: User opens Excel Document, provides inputs to Excel, and completes template. There is no interaction between the inputs in Excel and the contents of the template.
I'm trying to build out this process such that once they edit the embedded Word Document the user hits a button. The VBA code would then take the contents of the embedded Word document and paste (formatting and all) it as the body of the email. The file would attach itself to that email, and off it would go for approval.
I've been able to locate code to get me part of the way there, and to give props where props are due, I located the code here (see below for the code)
But this doesn't retain the Word Document's Formatting. Any recommendations? Maybe if I could extract the Word contents as HTML that would work. But not sure how to do that. All help appreciated.
Sub Test()
Dim Oo As OLEObject
Dim wDoc As Object 'Word.Document
'Search for the embedded Word document
For Each Oo In Sheet8.OLEObjects
If InStr(1, Oo.progID, "Word.Document", vbTextCompare) > 0 Then
'Open the embedded document
Oo.Verb xlVerbPrimary
'Get the document inside
Set wDoc = Oo.Object
'Copy the contents to cell A1
wDoc.Content.Copy
With Sheet8.Range("M1")
.PasteSpecial xlPasteFormats
.PasteSpecial xlPasteValues
End With
'Select any cell to close the document
Sheet8.Range("M1").Select
'Done
Exit For
End If
Next
Set wDoc = Nothing
End Sub
After reviewing comintern's code, I was getting an error I couldn't solve for. I went back to the boards and located some additional code. Merging the two seems to have fixed it.
Sub HTMLExport()
Dim objOnSheet As oleObject
Dim strFileName As String
Dim sh As Shape
Dim objWord As Object ''Word.Document
Dim objOLE As oleObject
Sheet8.Activate
Set sh = ActiveSheet.Shapes("RA_Template")
sh.OLEFormat.Activate
Set objOLE = sh.OLEFormat.Object
Set objWord = objOLE.Object
ActiveSheet.Range("M1").Activate
''Easy enough
strFileName = CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\temp.html"
objWord.SaveAs2 Filename:=strFileName, FileFormat:=10 '10=wdFormatFilteredHTML
'Copy the file contents into cell M1...
Dim handle As Integer
handle = FreeFile
Open strFileName For Input As handle
Sheet8.Range("M1").Value = Input$(LOF(handle), handle)
Close handle
'Delete the Temp File (strFileName)
Kill strFileName
'Select any cell to close the document
Sheet8.Range("M1").Select
End Sub`
If getting it into HTML will work (Word makes pretty ugly HTML...), you can just save it to a temp file and then pick it back up:
Sub HTMLExport()
Dim Oo As OLEObject
'Search for the embedded Word document
For Each Oo In Sheet8.OLEObjects
If InStr(1, Oo.progID, "Word.Document", vbTextCompare) > 0 Then
Dim temp As String
'GetSpecialFolder(2) gives the user's temp folder.
temp = CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\temp.html"
'10 = wdFormatFilteredHTML
Oo.Object.SaveAs2 temp, 10
'Copy the file contents into cell M1...
Dim handle As Integer
handle = FreeFile
Open temp For Input As handle
Sheet8.Range("M1").Value = Input$(LOF(handle), handle)
Close handle
'...and delete the temp file.
Kill temp
'Select any cell to close the document
Sheet8.Range("M1").Select
'Done
Exit For
End If
Next
End Sub
Note that if you're using this method, you can't open the embedded Word document after you get the OLEObject or Word won't allow you to save it.
I'm trying to copy the values from a named range in Excel to a bookmark in Word. I found this code on the web that does it in Excel VBA, but I'm getting an Error 13.
Set pappWord = CreateObject("Word.Application")
Set docWord = pappWord.Documents.Add(Path)
'Loop through names in the activeworkbook
For Each xlName In wb.Names
'if xlName's name is existing in document then put the value in place of the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName.Value)
End If
Next xlName
'Activate word and display document
With pappWord
.Visible = True
.ActiveWindow.WindowState = 0
.Activate
End With
I know that the line that is causing the error is:
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName.Value)
What am i doing wrong? Also, how & where would I code so that I can export the doc to PDF?
Thanks in advance.
Note: I've already selected the reference to the Microsoft Word (version number 14) Object model in Excel
so I use it to accomplish this task but taking an image from formatted Excel table.
Sub FromExcelToWord()
Dim rg As Range
For Each xlName In wb.Names
If docWord.Bookmarks.Exists(xlName.Name) Then
Set rg = Range(xlName.Value)
rg.Copy
docWord.ActiveWindow.Selection.Goto what:=-1, Name:=xlName.Name
docWord.ActiveWindow.Selection.PasteSpecial link:=False, DataType:=wdPasteEnhancedMetafile, Placement:= _
0, DisplayAsIcon:=False
End If
Next xlName
End Sub
Just curious... Why are you adding a document rather than opening the relevant doc which has the bookmarks? Try this code (I usually test the code before posting but I haven't tested this particular code. Just quickly wrote it)
Also I am using Late Binding so no reference to the Word Object Library is required.
Sub Sample()
Dim wb As Workbook
Dim pappWord As Object, docWord As Object
Dim FlName As String
Dim xlName As Name
FlName = "C:\MyDoc.Doc" '<~~ Name of the file which has bookmarks
'~~> Establish an Word application object
On Error Resume Next
Set pappWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set pappWord = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
Set docWord = pappWord.Documents.Open(FlName)
Set wb = ActiveWorkbook
For Each xlName In wb.Names
'if xlName's name is existing in document then put the value in place of the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName).Value
End If
Next xlName
'Activate word and display document
With pappWord
.Visible = True
.ActiveWindow.WindowState = 0
.Activate
End With
End Sub
EDIT
Changed
Range(xlName.Value)
to
Range(xlName).Value
Now the above code is TRIED AND TESTED :)
I haven't found anything that can help me.
I'm trying to open a certain word file, have some data written in it and saved under a different name. This is what I have so far:
Dim appWD As Word.Application
Set appWD = CreateObject("Word.Application.8")
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open("C:\Documents and Settings\Excel macro\Standaard.docx")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
Copy all data from Design
Sheets("Design").Select
Range("A1:G50").Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs Filename:=ThisWorkbook.Path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
At the moment all it does is; open the Standaard.docx file, open a new file and paste everything in the new file and saves. It should open the Standaard.docx file, paste it in there and save under a new name.
Many thanks!
The reason that it opens a new document is because you have the line:
appWD.Documents.Add
in your code before the line:
appWD.Selection.Paste
if you remove the appWD.Documents.Add Word will paste into your active document (i.e. "Standaard.docx").
Just one other point, you do not need the line:
Set appWD = CreateObject("Word.Application.8")
as you immediately initialise a new Word application in the line below it with:
Set appWD = New Word.Application
This macro opens a file then saves it as a new file name in a different folder based on info updated in the sheet1 of the Excel file
Sub OpenDocFileNewName()
'
' OpenDocFileNewName Macro
'
'
Set WordApp = CreateObject("Word.Application.8")
Set WordDoc = WordApp.Documents.Open("C:\Users\mmezzolesta\Documents\_TestDataMerge\STANDARD.docx")
WordApp.Visible = True
'
'
'Save as new file name
Sheets("Sheet1").Select
WordApp.ActiveDocument.SaveAs Filename:=("C:\Users\mmezzolesta\Documents\_TestMailMergeAuto") & "/" & Range("A2") & "Standard-Grounding-" & Range("e2").Text
WordApp.ActiveDocument.Close
WordApp.Quit
'
'
End Sub