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
Related
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.
I have an excel spreadsheet that is linked to multiple Word documents (.docx), which act as templates.
I have written a macro that opens the required word template from excel (the template chosen is dependent on the value of cell M17). The links in the word template update automatically as word opens. I am then trying to break the links of the document that I opened. This is what I have so far:
Function FnOpeneWordDoc()
Dim objWord
Dim objDoc
Dim path As String
path = Range("M17")
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("*file_path*" & path & ".docx")
objWord.Visible = True
Application.Wait (Now + TimeValue("0:00:30"))
objDoc.Fields.Unlink
End Function
I suspect that it isn't working because the macro is trying to break the links before the document has fully loaded (and therefore the existing links haven't had a chance to update?), which is why I added the wait. Unfortunately this doesn't seem to be the solution.
The above code would have been fine, but I didn't realise that the code had to be different if the text was in textboxes.
I struggled to break the links within textboxes, and kept getting run-time error 438. However, I found a workaround:
I wrote a sub in the word documents:
Sub Unlink
Selection.Fields.Unlink
End Sub
I then called this macro from my excel document:
Sub FnOpeneWordDoc()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("filename")
objWord.Visible = True
For i = 1 To objDoc.Shapes.Count
objDoc.Shapes(i).Select
objDoc.Application.Run ("unlink")
Next
End Sub
I'm performing several prints of embedded Word document witch has some fields linked to some cells, by my PrintOut macro, in a For..Next loop, as below.
I need after each print task, that the program wait for document to close and then doing the next print.
In this situation I receive error. Can anyone help ?
Sub contract()
Dim i As Integer
For i = 1 To 100
Cells(Sheets("SheetName").ListObjects("StaffInfo").ListRows.Count + 9, 8).Value = i
General.PrintIt ("EmbeddedDoc") 'Doc has many linked fields
Next i
End Sub
Print method
Sub PrintIt(P As String)
Dim objWord As Object
Dim ObjDoc As Object
Dim Oshp As Object
Application.ScreenUpdating = False
ActiveSheet.OLEObjects(P).Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set ObjDoc = objWord.ActiveDocument
ObjDoc.Fields.Update
For Each Oshp In ObjDoc.Content.ShapeRange
Oshp.TextFrame.TextRange.Fields.Update
Next
ObjDoc.PrintOut Background:=False
ObjDoc.PrintOut
objWord.Quit SaveChanges:=False
Application.ScreenUpdating = True
End Sub 'Print it
Introduced problem was solved by this code.
Above code do open and close embedded word document, 100 times, and that problem was happening in close document.
Exactly, I cant understand why closing document immediately after printout command that where after open and update fields, generating that error.
Thus I cleaned the problem ask!
By integrating "PrintIt" method in "Contract" method that is parent of that, without calling "PrintIt" for each document printout, embedded document opens each one, perform doc links updating and printing 100 times in for next loop and close word app and document, at last, each one too.
In short, I cant find reason of problem in several Open-Print-Close document in order immediately; But i change the algorithm to Open-Several print-Close and problem been cleaned!
Sub contract()
Application.ScreenUpdating = False
Sheets("SheetName").Unprotect
'Declare variables
Dim i As Integer
Dim objWord, ObjDoc As Object
'Core
ActiveSheet.OLEObjects("Contract").Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set ObjDoc = objWord.ActiveDocument
For i = 1 To 100
Cells(x, y).Value = i 'A specific cell that
' word embedded document fields are linked to
'corresponding fields they values change
'by changing this cell.
ObjDoc.Fields.Update
ObjDoc.PrintOut Background:=False
ObjDoc.PrintOut
Next i
objWord.Quit SaveChanges:=False
Sheets("SheetName").Protect AllowFiltering:=True
End Sub
Hoping that someone can give some advice, as I've modified my code many times now trying to get the AutoFitBehavior formatting to apply correctly. The code runs through everything as is (moves everything over and completes just fine), but the AutoFit never applies. Feel like I'm missing something that should be a simple fix, but everything I see seems to be telling me that the objWord.ActiveDocument.Tables(1).AutoFitBehavior wdAutoFitWindow should work - I've tried it within its' own If statement where it is now, as well as moving it around and including in different places, with the same result. Any advice is greatly appreciated.
Most recent version of my code:
Sub CopyToWord()
Dim objWord
Dim objDoc
Dim ws As Worksheet
Dim Rpt As Range
Application.CopyObjectsWithCells = False
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set ws = ThisWorkbook.Worksheets("Report")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
LastColumn = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
ws.Range("A1:" & Split(ws.Cells(, LastColumn).Address, "$")(1) & LastRow).Copy
With objWord
.ActiveDocument.PageSetup.Orientation = 1
.Selection.Paste
.Visible = True
End With
If objWord.ActiveDocument.Tables.Count <> 0 Then
objWord.ActiveDocument.Tables(1).AutoFitBehavior wdAutoFitWindow
End If
Application.CopyObjectsWithCells = True
ThisWorkbook.Worksheets("Control Panel").Activate
End Sub
Have you checked that the tables count condition is true (using debug.print)?
If not, I don't believe that an Excel Range object is simply converted into a table object in Word. You should probably use Range.ConvertToTablemethod so you can get the table object and then you can apply the auto fit thing.
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