VBA-carriage returns - vba

new here, and in VBA in general. I have created a macro that copies the contents of a cell in excel and pastes in a specific location in a word document. FYI, i use bookmarks in word to select the exact location for pasting. the issue is that everything copied inserts a line and/or paragraph/carriage return. i have found a lot of possible solutions but none of them work, prob given my inexperience in VBA. Please help!
Sub OpenWord()
Dim WordApp As Object
Dim WordDoc As Object
Dim R1 As Object
Dim R2 As Object
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(Filename:="C:\Users\KG\Desktop\VBA WIP\FAfile.docx")
Set R1 = WordDoc.Bookmarks("b1")
Set R2 = WordDoc.Bookmarks("b2")
WordApp.Visible = True
WordApp.Activate
Sheets("Details INPUT").Range("H4").copy
R1.Select
WordApp.Selection.PasteAndFormat Type:=wdFormatSurroundingFormattingWithEmphasis
Application.CutCopyMode = True
Sheets("Details INPUT").Range("H7").copy
R2.Select
WordApp.Selection.PasteAndFormat Type:=wdFormatSurroundingFormattingWithEmphasis
Application.CutCopyMode = True
Set WordDoc = Nothing
Set WordApp = Nothing
Set R1 = Nothing
Set R2 = Nothing
End Sub

Try the following method, instead. As for Excel, when working with Word's object model it's better to use the underlying objects, rather than selecting. And it's also better to avoid using the Clipboard unless you absolutely need to. Word also has a Range object, which is a useful "target".
Note that this approach will lose any formatting in the Excel sheet.
If you want to bring across formatting, using the code in your question, then you will be bringing in the worksheet structure at the same time: you'll be pasting a table cell. That may be what you think is a new line/paragraph. The variation I include (see the three ''') pastes just the font formatting, without the Excel structures (equivalent to PasteSpecial as RTF in the UI).
Sub OpenWord()
Dim WordApp As Object
Dim WordDoc As Object
Dim R1 As Object
Dim R2 As Object
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(Filename:="C:\Users\KG\Desktop\VBA WIP\FAfile.docx")
Set R1 = WordDoc.Bookmarks("b1").Range
Set R2 = WordDoc.Bookmarks("b2").Range
WordApp.Visible = True
'Put it at the end, before "clean up" if you want to do this
'WordApp.Activate
R1.Text = Sheets("Details INPUT").Range("H4").Text
R2.Text = Sheets("Details INPUT").Range("H7").Text
'''Sheets("Details INPUT").Range("H7").copy
'''R2.PasteExcelTable False, False, True
'CutCopyMode is NOT boolean, pass it either 1 or 0 or the xl-constant value!
'''Application.CutCopyMode = xlCopy
Set R1 = Nothing
Set R2 = Nothing
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub

Multiple issues here.
At first since you are using late binding CreateObject("Word.Application") you probably not have included references to Microsoft Word ... Object Library. But then the constant wdFormatSurroundingFormattingWithEmphasis will not be set and be 0. Using late binding the constant names cannot be used. The appropriate values must be used instead.
And using Selection.PasteAndFormat you are pasting the whole table cell instead of only the value. As of your description you wants only pasting the value.
To pasting the value only try Selection.PasteSpecial:
...
Sheets("Details INPUT").Range("H4").Copy
R1.Select
'WordApp.Selection.PasteAndFormat Type:= 20
WordApp.Selection.PasteSpecial DataType:=2
Application.CutCopyMode = False
Sheets("Details INPUT").Range("H7").Copy
R2.Select
'WordApp.Selection.PasteAndFormat Type:= 20
WordApp.Selection.PasteSpecial DataType:=2
Application.CutCopyMode = False
...
Where the 2 is the value of wdPasteText.
If formatted content will be needed from Excel, then do using wdPasteRTF instead, which is 1 instead of 2.

Related

Only copy cells with data from Excel to Word

I need some further help developing my code. I have the basics down now with some earlier help but I am not sure on this next part.
The code I am designing will run in a spreadsheet whereby the amount of rows used in a sheet will vary depending on the amount of data being used. (Due to nature of business and Norwegian Laws, I can't go into more details.)
I'd like to have a Range of B5:B1000 as a standard range and only have cells containing data be auto filled into the template but I am unsure how to write said code. Could someone please advise how I am able to go about this?
All questions related to this have been based on copying from one sheet to another.
This is my code so far which I am using in excel:
Sub CopyRangeToWord()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\CoffeeFuelsMeNow\Documents\Custom Office Templates\EVERYTHING IS AWESOME.dotx")
Range("B5:B92").Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.PasteAndFormat (wdFormatPlainText)
End With
objWord.Visible = True
End Sub
This assumes that column B is compact (no holes in the data):
Sub CopyRangeToWord()
Dim objWord, N As Long
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.documents.Add
N = Cells(Rows.Count, "B").End(xlUp).Row
Range("B5:B" & N).Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.PasteAndFormat (wdFormatPlainText)
End With
objWord.Visible = True
End Sub

Using Word VBA to automate Excel, I get Run-time error '13': Type mismatch when using the .Find function

I'm trying to get data from an excel sheet to a word document. I try using the 'Find' function however I keep getting the same error "Type mismatch" on this line:
Set FoundRange = .Cells.Find(260707)
Here is the subroutine I am running.
Sub GetID()
Dim oXL As Object
Dim oWB As Object
Dim oSheet As Object
Dim WorkbookToWorkOn As String
Dim FoundRange As Range
Dim dummyvar As String
'Start a new instance of Excel
Set oXL = CreateObject("Excel.Application")
'Line to make Excel Visible or not
oXL.Visible = False
'Open the workbook
'Set the file path to access the 'Certified Personnel' table
WorkbookToWorkOn = "\\DataSource\CertifiedPersonnel.xlsx"
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
Set oSheet = oXL.ActiveWorkbook.Sheets("tblCertifiedPersonnel")
'End of Excel Automation. Everything from this point on can reference Excel.
With oSheet
dummyvar = .Cells(1, 2).Text
.Cells(1, 2).Select
'Set the range of the cell containing the ID number
'If the ID was found
Set FoundRange = .Cells.Find(260707)
If Not FoundRange Is Nothing Then
'Set the NTlogin equal to the value of column 1, and row corresponding to the FoundRange row
NTlogin = .Cells(FoundRange.Rows, 1).Text
Role = .Cells(FoundRange.Rows, 4).Text
End If
End With
'End Excel reference
oXL.ActiveWorkbook.Close SaveChanges:=False
oXL.Application.Quit
Set oXL = Nothing
Set oWB = Nothing
Set oSheet = Nothing
End Sub
I know it is accessing the correct workbook, because the dummy variable (dummyvar) is returning the value I expect. I have tried several things related to the 'Find' function, however I have not been able to get it to work. Any ideas? Much appreciated.
You are using late binding and have FoundRange declared as a Range. Since this is in a Word document, you're implicitly declaring it as a Word.Range here:
Dim FoundRange As Range
.Find is returning an Excel.Range. Change it to:
Dim FoundRange As Object
With the assumption that the ID values are stored as text in the worksheet, either with a cell type of Text or with an apostrophe/single-quote in front of the number, you may need to format the ID as string. With the further assumption that eventually you may want to pass the ID via parameter to the procedure, give this a try:
Set FoundRange = .Cells.Find(CStr(260707))
That will also allow you to replace the constant number with a variable if desired.

Inserting text in a embedded Word template, at a bookmark, from excel. "error 13 Type mismatch" error

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

Loop Copy/pasting data in NamedCells from excel into Word

I am working on Macro that copies data from NamedCells in Excel and places them at specific Bookmarks in a Word template. I am getting a run time error 9 when the code gets to the pasting data at Bookmarks line. Further, some of the data is getting pasted into the template but "Title1" is getting pasted at BookmarkTitle2 location and Title2 is getting pasted at BookmarkTitle3... then the run time error comes up...
Code is below....
Can someone tell me what I am doing wrong?
Sub CopyExcelTitlesToWord()
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim BookmarkArray As Variant
Dim Title(1 To 3) As Range
Dim x As Integer
'List the tables/charts from excel you want to Word
Set Title(1) = ThisWorkbook.Worksheets("TopPage").Range("Title1")
Set Title(2) = ThisWorkbook.Worksheets("TopPage").Range("Title2")
Set Title(3) = ThisWorkbook.Worksheets("TopPage").Range("Title3")
'List of corresponding Word Bookmarks to paste the tables/charts to in Word
BookmarkArray = Array("BookmarkTitle1", "BookmarkTitle2", "BookmarkTitle3")
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Open Word template
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
'Open existing template in Word
Set myDoc = WordApp.Documents.Open("C:\Users\xxx\Desktop\TemplateTest1.docx")
'Loop Through and Copy/Paste Multiple Excel NamedCells
For x = LBound(Title) To UBound(Title)
Title(x).Select
Selection.Copy
'Paste Title into MS Word (using inserted Bookmarks -> ctrl+shift+F5). 'Name the Bookmarks so they are in Series so they are easy to loop through.
myDoc.Bookmarks(BookmarkArray(x)).Range.PasteExcelTable False, False, True
Next x
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
BookmarkArray will be a 0 based array (0..2) - see Excel help on the Array function.
I suggest you change
Dim Title(1 To 3) As Range
to
Dim Title(0 To 2) As Range
and change the hard coded indexes accordingly.

Pasting a table into open Word document at a bookmark

I have searched a fair bit on this and other forums but I can't get code to work. I know this is user error - I am learning/self-taught at this.
What I want is to copy a (admittedly large) table in a specific Excel worksheet into an already-open Word document, at a specific point. I have seen this done using a keyword search but I would prefer to use a bookmark (and I've made the bookmark thing work!) purely because it's not visible to the end user. I'm trying to automate the creation of a document as much as possible.
The below code works, but I can only get it to work when the Word document in question is closed. If I try to run this sub when the word doc is open, it just tries to re-open it and of course can't. I can't find a neat bit of code that allows me to paste data into an already-open document.
Also, I can make this work for one value, but not for a range (i.e. the table I want to paste).
Sub ExcelRangeToWord()
Dim objWord As Object
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Summary")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'open the word doc
objWord.Documents.Open "K:\Exeter Office\Quotebuilder project\testbed\test.docx" 'change as required
'pastes the value of cell I19 at the "heatlosses" bookmark
With objWord.ActiveDocument
.Bookmarks("heatlosses").Range.Text = ws.Range("I19").Value
End With
'Optimize Code
Set objWord = Nothing
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
I'm trying to tackle this one step at a time, cos then I have half a chance of understanding things a bit better...
If I try and copy/paste a range, instead of just one value, I was using Currentregion to select all used cells surrounding B19:
With objWord.ActiveDocument
.Bookmarks("heatlosses").Range.Text = Range("B19").CurrentRegion
End With
All this does is paste the word "True" into Word.
I am baffled. Please, can anyone offer assistance?
Use the code below to achieve what you require:
Sub CopyToWord()
Dim wApp, wDoc
'Get the running word application
Set wApp = GetObject(, "Word.Application")
'select the open document you want to paste into
Set wDoc = wApp.documents("test.docx")
'copy what you want to paste from excel
Sheet1.Range("A1").copy
'select the word range you want to paste into
wDoc.bookmarks("heatlosses").Select
'and paste the clipboard contents
wApp.Selection.Paste
End Sub