I have a functioning script, it copies targeted text from an Excel sheet to an open Word document, but I'm wondering if it's possible that it also copies the formatting on the text, meaning some of the text is Bold and underlined. Currently, it just copies the text over to word.
Sub Updated_Excel_Data_to_Word()
Dim rYes As Range, r As Range
Dim sData As String
Dim tData As String
Dim uData As String
Dim objWord As Object
Set rYes = Range("B2:B34")
For Each r In rYes
If r = "X" Then
sData = sData & r.Offset(0, 1) & Chr(13)
End If
Next r
Set rYes = Range("F2", Range("F" & Rows.Count).End(xlUp))
For Each r In rYes
If r = "X" Then
tData = tData & r.Offset(0, 1) & Chr(13)
End If
Next r
Set rYes = Range("J2", Range("J" & Rows.Count).End(xlUp))
For Each r In rYes
If r = "X" Then
uData = uData & r.Offset(0, 1) & Chr(13)
End If
Next r
Set objWord = GetObject(, "word.application")
objWord.activeDocument.Bookmarks("One").Select
objWord.Selection.TypeText (sData)
objWord.activeDocument.Bookmarks("Two").Select
objWord.Selection.TypeText (tData)
objWord.activeDocument.Bookmarks("Three").Select
objWord.Selection.TypeText (uData)
End Sub
Yes, I think this should be possible but requires some structural changes to your code. You'll need to replicate the "paste" operation in Word, instead of (as you are currently doing) storing only the raw text in your
sData
,tData
,uData
variables.Let's also clean this up with an additional subroutine, since you're repeating the
For Each r
loop over a few different range objects.Here is some example output which has preserved all of the text formatting (bold, underline, font color, etc.)
This should work across all Office applications (see here for a similar Q&A regarding Excel->PowerPoint), and as mentioned:
The
CommandBars.ExecuteMso
is not very well-documented compared to many other methods. TheApplication.CommandBars
property reference doesn't even mention theExecuteMso
method, which I found some information about here:http://msdn.microsoft.com/en-us/library/office/ff862419(v=office.15).aspx
You'll need a list of idMso parameters to explore, which come as part of a rather large downloadable file, current for Office 2013 I believe:
http://www.microsoft.com/en-us/download/details.aspx?id=727