How to paste data to word doc - vb.net

I am using send-keys to select all data and copy it from another application. My goal is to paste this data into word and save as a PDF. The problem i seem to have, is that using Microsoft interop, requires you to programattically format the data. If i copy the data from the other application, and paste it manually in a real word doc, the format retains itself.
Is there a way to easily take my clipboard data and use it with this code?
Try
Dim oWord As Word.Application
Dim oDoc As Word.Document
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
oPara1 = oDoc.Content.Paragraphs.Add
oPara1.Range.Text = Clipboard.SetText
'TIll Above your entire odoc is formatted
'From below I will save it to my own code
Dim newdoc As Word.Document
newdoc = oDoc
newdoc.SaveAs2("K:\file.pdf", Word.WdSaveFormat.wdFormatPDF)
'All done. Close this form.
'BSPGlobals.DataBase.Contact.ExitApp()
MessageBox.Show("Print to Doc Done.")
Catch ex As Exception
MessageBox.Show("Error at Printing the bill." & vbCrLf & ex.Message)
End Try

Depending on the source and format of the Clipboard data, you can influence the way the Clipboard contents is pasted into Word by fiddling around with the following Application options (don't forget to restore the original settings when you are done):
' when pasting between different Office documents
oWord.Options.PasteFormatBetweenDocuments = Word.WdPasteOptions.wdKeepSourceFormatting
' when contents is copied from a document that uses styles
oWord.Options.PasteFormatBetweenStyledDocuments = Word.WdPasteOptions.wdKeepSourceFormatting
' when pasting from an external source such as a web page
oWord.Options.PasteFormatFromExternalSource = Word.WdPasteOptions.wdKeepSourceFormatting

Related

Pasting multiple images in a word doc

I need assistance in building a macro that would take the image that is stored in the clipboard and paste it in the word doc. There will be multiple images so sequential images must be pasted at the end of the document.
Here is my current code so far
' Create word document and paste to word
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
wordobj.Visible = True
Set objSelection = wordobj.Selection
objSelection.Paste
' Paste in the active end of the word document
'??? tried multiple lines but it gives "object" error
objdoc.ActiveDocument.Content
objdoc.Collapse Direction:=wdCollapseEnd
objSelection.Paste.Paste
Any assistance will be helpful
Since your code creates a new document each time it's run, the only way there'd be anything to paste over is if that new document already has some content. But since you don't even specify a template to load from, that can only mean Word's 'Normal' template, which should never have any content. Regardless, it's as simple as:
Sub Demo()
Dim wordobj As Object, objdoc As Object
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
With objdoc.Range
.InsertAfter vbCr
.Characters.Last.Paste
End With
End Sub

Copying contents of Word doc to newly created Word doc from excel VBA

I am trying to use excel data to perform various tasks on a word document. However, this will be used by other people, so I wanted to copy all contents from the word doc (and formatting and tables) to a new word doc and edit the new one to prevent others from accidentally saving over the first one (template one). I also want to close the template (first) doc and keep the second (new) one open.
I am new to VBA and am having trouble understanding how to handle this. After a bunch of googling, I've compiled this (not working) code:
Dim WordApp As Object
Dim WordDoc As Word.Document
Dim NewWordDoc As Word.Document
'Dim other stuff'
'-------------------------------------------------------------------
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open("C:\Users\Windows\Documents\CRC Labels
test.doc")
Set NewWordDoc = WordApp.Documents.Add 'I think this gives an error'
'------------------------------------------------------------------------
'Line that actives WordDoc'
Selection.WholeStory 'Select whole document
Selection.Expand wdParagraph 'Expands your selection to current paragraph
Selection.Copy 'Copy your selection
'Line that closes WordDoc'
'Line that activates NewWordDoc'
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content
'------------------------------------------------------------------------
'Do stuff with NewWordDoc'
'------------------------------------------------------------------------
Set WordDoc = Nothing
Set WordApp = Nothing
Any other ideas of handling this situation? Thank you for your response.
When you find yourself using an existing document as the basis for creating new documents it's time to consider saving that document as a Word Template. This is a particular type of file (*.dotx or *.dotm) that may contain
boiler-plate text
Building blocks with additional boiler-plate to be inserted as required
styles (formatting command sets)
customized keyboard shortcuts
Ribbon customizations
VBA code (macros, in *.dotm, only)
that will be inherited and/or shared by all documents generated from the template.
In order to create a new document from a template, use the Documents.Add method, specifying the path and file name:
Dim wdDoc as Word.Document
Set wdDoc = Documents.Add(path & filename)
'From outside Word: Set wdDoc = wdApplication.Documents.Add
This will create a new document from the template, copying the complete template content without affecting the template, itself.
Note: You can also use a "plain document" (*.docx) with the Documents.Add method and it will copy the content. It will not, however, link back to that document so it can't share macros, for instance.

Automation of PDF String Search using Excel VBA - OLE error

I'm getting this error, "Microsoft Excel is waiting for another application to complete an OLE action" when trying to automate a PDF string search and record findings in excel. For certain PDFs this error is not popping. I assume this is due to the less optimized PDFs taking a longer time to search string while indexing page by page.
To be more precise, I have a workbook containing two sheets. One contains a list of PDF file names and the other has a list of words that I want to search. From the file list the macro would open each PDF file and take each word from the list of words and perform a string search. If found it would record each finding in a new sheet in the same workbook with the file name and the found string.
Below is the code I'm struggling with. Any help is welcome.
Public Sub SearchWords()
'variables
Dim ps As Range
Dim fs As Range
Dim PList As Range
Dim FList As Range
Dim PLRow As Long
Dim FLRow As Long
Dim Tracker As Worksheet
Dim gapp As Object
Dim gAvDoc As Object
Dim gPDFPath As String
Dim sText As String 'String to search for
FLRow = ActiveWorkbook.Sheets("List Files").Range("B1").End(xlDown).Row
PLRow = ActiveWorkbook.Sheets("Prohibited Words").Range("A1").End(xlDown).Row
Set PList = ActiveWorkbook.Sheets("Prohibited Words").Range("A2:A" & PLRow)
Set FList = ActiveWorkbook.Sheets("List Files").Range("B2:B" & FLRow)
Set Tracker = ActiveWorkbook.Sheets("Tracker")
'For each PDF file list in Excel Range
For Each fs In FList
'Initialize Acrobat by creating App object
Set gapp = CreateObject("AcroExch.App")
'Set AVDoc object
Set gAvDoc = CreateObject("AcroExch.AVDoc")
'Set PDF file path to open in PDF
gPDFPath = fs.Cells.Value
' open the PDF
If gAvDoc.Open(gPDFPath, "") = True Then
'Bring the PDF to front
gAvDoc.BringToFront
'For each word list in the range
For Each ps In PList
'Assign String to search
sText = ps.Cells.Value
'This is where the error is appearing
If gAvDoc.FindText(sText, False, True, False) = True Then
'Record findings
Tracker.Range("A1").End(xlDown).Offset(1, 0) = fs.Cells.Offset(0, -1).Value
Tracker.Range("B1").End(xlDown).Offset(1, 0) = ps.Cells.Value
End If
Next
End If
'Message to display once the search is over for a particular PDF
MsgBox (fs.Cells.Offset(0, -1).Value & " assignment complete")
Next
gAvDoc.Close True
gapp.Exit
set gAVDoc = Nothing
set gapp = Nothing
End Sub
I have now found the answer to this problem.
I'm using Acrobat Pro and whenever I open a PDF file, it opens with limited features due to Protected View settings. If I disable this function or if I click Enable All Features and save changes to the PDF files, VBA macro runs smooth.
It's funny, I'm posting an answer to my own problem.

Add Word docs to Word App without saving to Filesystem

I'm trying to create word documents on the fly in VB.NET, and I've found that the documentation on all of this seems very scarce. Right now my program works by looping through a database table, and for each row it pulls out the variables. The program then loops through and parses a template word doc, replacing variables in that template with variables from the database, then saving as a new doc.
Instead, for every "new doc" that I would be creating, I want to just append it onto another doc, that way when it comes time to parse 1000 rows in the table, I don't have to create and save 1000 different word documents to the filesystem.
I can't seem to find anything out there about this. Everything mentions merging documents (I actually want to append, not merge) or the only way I can append ("Insert") a document is by using WordApplication.Selection.InsertFile(newWordDocument.FullName). This works, but requires me to save newWordDocument to the filesystem before inserting it.
Is there a way to, while still in memory, add newWordDocument to my WordApplication object?
Here's the pseudocode of what I have now
For each row in TableOfVariables
Dim WordApplication as New Word.Application
Dim tempDoc as New Word.Document
tempDoc = WordApplication.Documents.Add
tempDoc = fillVariablesOfTheDocument(tempDoc, row)
tempDoc.Save() 'This is the problem - it saves as a new file rather than appending into WordApplication
Next
You didn't make an assignment, just a statement with
objWordApp.Documents.Add(tempDoc) 'This is where the problem is!
Dim wordApp as new Microsoft.Office.Interop.Word.Application
wordApp.Visible = true
Dim doc as Word.Document
doc = wordApp.Documents.Add
and you don't have to save it until you are good and ready. This also works
Dim Word As Word.Application
Dim Doc As Word.Document
'Start Word and open the document template.
Word = CreateObject("Word.Application")
Word.Visible = True
Doc = Word.Documents.Add
from http://support.microsoft.com/kb/316383
Took a while, but somehow I found out about MailMerge, which I had no idea existed. Long story short, I can have a template document with variables, and I can have an input excel document. The excel document will have a header row which contains the variable names, and each individual cell of the excel doc will represent the variable that will go into the document. When I execute MailMerge, the template will be replaced with n amount of pages (where n is the number of excel rows). This solves my problem of adding multiple documents to 1 big excel document. I tested this with 1,000 rows in my excel doc, and it worked flawlessly.
Here's the code I ended up with:
Dim wrdSelection As Word.Selection
Dim wrdMailMerge As Word.MailMerge
Dim wrdMergeFields As Word.MailMergeFields
' Create an instance of Word and make it visible.
wrdAppMailMrg = CreateObject("Word.Application")
wrdAppMailMrg.Visible = True
' Add a new document.
wrdDocMailMrg = wrdAppMailMrg.Documents.Open("Template.docx")
wrdDocMailMrg.Select()
wrdSelection = wrdAppMailMrg.Selection()
wrdMailMerge = wrdDocMailMrg.MailMerge()
'Open Data Source
wrdDocMailMrg.MailMerge.OpenDataSource("InputVariables.xlsx", SQLStatement:="SELECT * FROM [Sheet1$]")
' Perform mail merge.
wrdMailMerge.Destination = _
Word.WdMailMergeDestination.wdSendToNewDocument
wrdMailMerge.Execute(False)
' Close the original form document.
wrdDocMailMrg.Saved = True
wrdDocMailMrg.Close(False)
' Release References.
wrdSelection = Nothing
wrdMailMerge = Nothing
wrdMergeFields = Nothing
wrdDocMailMrg = Nothing
wrdAppMailMrg = Nothing
Now I just have to tweak it to make it run faster and clean up the UI, but the functionality is completely there.

Save Word document in a different format without effective active document

Is there a way in VB.net to save a Word document as a different format (i.e. Me.Application.ActiveDocument.SaveAs) without switching to it? For example, if the current document is an unsaved, I want to save an copy of that document as HTML but still keep the unsaved document active.
Copy the current doc variable to another variable and save it.
Try
Dim oWord As Word.Application
Dim oDoc As Word.Document
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(5.08)
oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(4.57)
oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1.27)
oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(3.81)
oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints(29.7)
oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints(21)
'TIll Above your entire odoc is formatted
'From below I will save it to my own code
Dim newdoc As Word.Document
newdoc = oDoc
newdoc.SaveAs2("d:\file.pdf", Word.WdSaveFormat.wdFormatPDF)
'All done. Close this form.
'BSPGlobals.DataBase.Contact.ExitApp()
MessageBox.Show("Print to Doc Done.")
Catch ex As Exception
MessageBox.Show("Error at Printing the bill." & vbCrLf & ex.Message)
End Try