Let me preface this by saying I'm very new to VBA, so any help is appreciated.
I have been approached by someone to see if I can create a basic level of automation.
The need is to export data from Excel into Word with a button push.
The end goal is to have fields of data within excel such as "First name" "Surname" "Address"
"Contact Number". Then select say an entire row of a person (B1,B2,B3,B4) and when the Macro button is pressed, it opens a word document and pre-fills the fields into the document. It is to prefill letters for sending, this person has also stated that mail merge does not do what they need. Below is what I'm working with.
Sub ExcelToWord()
Dim wordApp As Word.Application
Dim mydoc As Word.Document
Set wordApp = New Word.Application
wordApp.Visible = True
Set mydoc = wordApp.Documents.Add()
ThisWorkbook.Worksheets("sheet1").Range("").Copy
mydoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
mydoc.SaveAs2 "MyDoc"
End Sub
This allows for a specific range such as (A2,B3) However not the "Selected" area.
I apologise if this is very basic but as I said, I don't really use VBA.
If I understanding your question, I think you only need to replace:
ThisWorkbook.Worksheets("sheet1").Range("").Copy
by:
Selection.Copy
It seems you need to use the Application.Selection property which returns the currently selected object on the active worksheet for an Application object.
Sub ExcelToWord()
Dim wordApp As Word.Application
Dim mydoc As Word.Document
Set wordApp = New Word.Application
wordApp.Visible = True
Set mydoc = wordApp.Documents.Add()
ThisWorkbook.Worksheets("sheet1").Activate()
Application.Selection.Copy()
mydoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
mydoc.SaveAs2 "MyDoc"
End Sub
Related
So we have this table we are using at the office. I changed the Column Name and Content for confidentiality purposes.
We're trying create a Word Document for each ID consisting of all the Name's and Surnames for that ID only from our Excel file.
i.e. A new Word Document is created for ID1. The contents are all the Names and Surnames only for that ID1 excluding the Column Name. Another Word Document will be created for the next ID available until all IDs have their own document,
So far this is what I got:
Sub test()
Dim copyRng As Range
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Set copyRng = Range("B2:C" & lastrow)
Range("B2:C" & copyRng.Rows.Count).Select
Selection.Copy
'Declare Word Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
'Create a new instance of Word
Set WrdApp = New Word.Application
WrdApp.Visible = True
WrdApp.Activate
'Create a new Document in the Word Application
Set WrdDoc = WrdApp.Documents.Add
WrdDoc.Activate
WrdDoc.Range(WrdDoc.Characters.Count - 1).Paste
End Sub
I can't seem to copy only the rows for a specific ID.
Can anyone suggest a better solution copy only the cells based on the IDs?
I simplified my problem in the meantime.
First I select the cells I want to be copied over to a Word Document.
Then I run this code:
Selection.Copy
'Declare Word Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
'Create a new instance of Word
Set WrdApp = New Word.Application
WrdApp.Visible = True
WrdApp.Activate
'Create a new Document in the Word Application
Set WrdDoc = WrdApp.Documents.Add
WrdDoc.Activate
With WrdDoc.Range(WrdDoc.Characters.Count - 1).Characters.Last
.PasteExcelTable False, True False
With .Tables(1)
.AutoFitBehavior wdAutoFitWindow
End With
.InsertAfter Chr(1)
End With
This way, I just have to highlight the cells I want to be copied over to Word and Run the Macro. The Macro will create a new Word Document for me.
1) I open a pdf using Microsoft word, through excel VBA.
2) From the word doc, I wish to copy only page 3 and page 4 (these two are tables without captions) into excel
3) at the moment, I could only copy the entire word doc into the excel, which can be troublesome.
below is my code:
Sub convertpdftowordthenexcel()
Dim wordapp As Word.Application
Dim input1 As String
input1 = "C:\Users\Me\Desktop\Fruitjuice.pdf"
'open pdf in word
Set wordapp = New Word.Application
wordapp.documents.Open Filename:=input1, Format:="PDF Files", ConfirmConversions:=False
wordapp.Visible = True
'copy the content of the word file
wordapp.ActiveDocument.Content.Copy '<------this is where I want to change
'go to excel and paste it there
Workbooks("openpdfusingdoc.xlsm").Worksheets("Sheet1").Activate
Worksheets("Sheet1").Activate
Cells(1, 1).Select
ActiveSheet.PasteSpecial Format:="Text"
wordapp.Quit savechanges:=wdDoNotSaveChanges
End Sub
Any suggestion on how to do this?
Thanks so much guys!
You can access tables through the tables collection - you may need to workout what index number the two you want are, I've assumed they're the first two in the document
Sub convertpdftowordthenexcel()
Dim wordapp As Word.Application
Dim input1 As String
input1 = "C:\Users\Me\Desktop\Fruitjuice.pdf"
'open pdf in word
Set wordapp = New Word.Application
wordapp.documents.Open Filename:=input1, Format:="PDF Files", ConfirmConversions:=False
wordapp.Visible = True
'copy the first two tables of the word file
wordapp.ActiveDocument.tables(1).range.Copy
'go to excel and paste it there
with Workbooks("openpdfusingdoc.xlsm").Worksheets("Sheet1")
.Cells(1, 1).PasteSpecial Format:="Text"
wordapp.ActiveDocument.tables(2).range.Copy
.cells(.rows.count,1).end(xlup).offset(2,0).pastespecial format:="Text"
end with
wordapp.Quit savechanges:=wdDoNotSaveChanges
End Sub
(PS Never use Select)
In my vba code I need to go to the end of the word document.
The vba is written and executed from Excel.
The statement : Selection.EndKey unit:=wdStory, Extend:=wdMove " will not run.
Can anyone explain where I do the mistyping.
I have tried to use the statement in other vba codes, but without success.
Sub InsertFromFilesTestEnd()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = New Word.Application
Set wrdDoc = wrdApp.Documents.Open("c:\users\peter\documents\direkte 0302 1650.docm")
wrdApp.Visible = True
wrdApp.Activate
Application.ScreenUpdating = False
Selection.EndKey unit:=wdStory, Extend:=wdMove
End Sub
Hopefully you can guide me to the end of my document. When so, I am sure I can use "selection" to move around in the document.
The issue here is that Selection isn't qualified to which application's Selection you are wanting. As such, it's using the default for Excel VBA, which would be the Excel Application in which the VBA was launched. Implicitly you are saying:
Application.Selection.EndKey unit:=wdStory, Extend:=wdMove
The error is because Excel's Application.Selection object doesn't have an EndKey method and so VBA has no idea what you are trying to do here.
Instead you want to qualify that Selection with the instance of the Word.Application object you are already working with:
wrdApp.Selection.EndKey unit:=wdStory, Extend:=wdMove
Using Selections in cases like this is quite unnecessary. Aside from being inefficient, it's also prone to producing a lot of screen flicker. Try, for example:
Sub InsertFromFilesTestEnd()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = New Word.Application
With wrdApp
.Visible = True
.ScreenUpdating = False
Set wrdDoc = .Documents.Open("c:\users\peter\documents\direkte 0302 1650.docm")
With wdrDoc
.Range.Characters.Last.InsertFile FileName:="MyFileName", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
End With
.Activate
.ScreenUpdating = True
End With
End Sub
I'm creating an Excel document that, among other things, copies a few arrays of data into a Word file.
Everything is working absolutely fine except that, when it pastes the selection I'm interested in, it pastes it infinitely until I intervene by taking down Word via Task Manager.
There is no reason, as far as I can see, for it to loop. So I'm pretty clueless of what to do next, and I was hoping you guys would shed a light into what I'm doing wrong. The concept is as follows:
Sub TestA()
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Opening app and document
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open("C:\Users\RCO1\Desktop\Teste VBA\2. Conceptual Testing\Export\XLWDTST.docx")
Set wdbmRange = wdDoc.Bookmarks("TableInsertion").Range
'Selecting array
Sheets("ExportMe").Select
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
'Pasting data
With wdbmRange
.PasteSpecial '<------- it simply goes back up to the beginning of the code at this point
CutCopyMode = False
End With
'Closing and saving
wdDoc.Save
wdDoc.Close
wdApp.Quit
Set wdApp = Nothing
Set wdDoc = Nothing
End Sub
Just note that I can't simply transform this array into a table so to speak for formatting reasons.
After placing a few inquiries, I have been given the following simple, yet very effective, piece of code:
Set wdApp = CreateObject("Word.Application")
Filepath = Sheets("Proposal Generator").Range("I9")
Set wdDoc = Word.Documents.Open(Filepath)
with wdDoc
Sheets("Shhet1").Cells(1).CurrentRegion.Copy
.Bookmarks("TableInsertion").Range.PasteExcelTable 0, 0, 0
.SaveAs (TxtSaveFolder.Text & "\" & TxtFileName.Text)
End With
I hope this works for anyone who's trying to export tables.
I'm trying to copy a series of charts in one sheet to one document in word, but for some reason I only get the latest paste (meaning the last chart on the sheet). I know that the iteration goes through all charts, becausewhen I modofiy the code to print a single word doc for each chart it does so, but I want the charts together, so please help me out
The code:
Sub ChartsToWord()
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim iCht As Integer
Dim Msg As String
Set WDApp = CreateObject("Word.Application")
Set WDDoc = WDApp.Documents.Add
For iCht = 1 To ActiveSheet.ChartObjects.Count
' copy chart as a picture
ActiveSheet.ChartObjects(iCht).Chart.CopyPicture _
Appearance:=xlScreen, Size:=xlScreen, Format:=xlPicture
WDDoc.Content.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, DisplayAsIcon:=False
WDDoc.Content.InsertParagraphAfter
Next
WDDoc.SaveAs ("C:\Users\confidential\Documents\charts.doc")
WDDoc.Close ' close the document
' Clean up
Set WDDoc = Nothing
Set WDApp = Nothing
End Sub
Please replace beginning of PasteSpecial line into:
WDApp.Selection.Range.PasteSpecial ... 'and so on
In your situation you paste chart into whole document instead of current paragraph.
One more suggestion. You could use the following to insert new paragraph:
WDApp.Selection.MoveEnd wdStory
WDApp.Selection.Move