From Excel using VBA I want to copy a range from Excel to Word and I'm stuck!
I'm trying to recreate what I do manually by:
Select a Range of cells and COPY
Open a Word Doc
Select "Paste Special" and "Formatted Text (RTF)"
I've tried multiple versions of code that I've found on the internet but I am unable to get the code to run. I do have the "Microsoft Word 16.0 Object Library" Checked as a reference in Excel.
The Error I get is "Run Time Error 91 - Object Variable or With Block Variable not set". I have marked in the code below where it fails. When I run this it launches Word but it does not open a new document.
Here's the code that has gotten me the farthest.
Sub ExcelToWord()
Dim PageNumber As Integer
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim FileToOpen As String
Dim strPath As String
FileToOpen = "Excel Link test.docx"
strPath = "C:\"
'the next line looks to a cell to decide what page number to scroll to
PageNumber = 1 'Later
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
Else
On Error GoTo notOpen
Set wrdDoc = wrdApp.Documents(FileToOpen)
GoTo OpenAlready
notOpen:
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
End If
OpenAlready:
On Error GoTo 0
Range("A6:D11").Copy ' med WS Name
With wrdApp
'------> Fails Here
.Selection.Goto What:=1, Which:=2, Name:=PageNumber
.Visible = True
.Selection.Paste
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
As always, thanks for your help!
Please, test the next code. It will open a new blank document and use it instead of the one being open by code:
Sub ExcelToWord()
Dim PageNumber As Integer, wrdApp As Word.Application, wrdDoc As Word.Document
Dim sh As Worksheet
Set sh = ActiveSheet 'use here the sheet you need
PageNumber = 1
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
err.Clear: On Error GoTo 0
Set wrdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wrdDoc = wrdApp.Documents.Add 'add a blank document
wrdApp.Visible = True 'make Word application visible
'only for debugging, if not want to be visible
'and you will save it (programmatically) in the next steps...
sh.Range("A6:D11").copy ' med WS Name
With wrdApp
.Selection.Goto What:=1, which:=2, Name:=PageNumber
.Visible = True
.Selection.Paste
End With
Set wrdDoc = Nothing: Set wrdApp = Nothing
End Sub
Related
I have a list of pages that I want to delete in MS Word such as Page number : 5 to 10 , 12 to 16 etc. through MS Excel VBA.
I found a code to delete continuous pages through MS Excel VBA but when I run it gives "The Requested member of the collection does not exist" error." How can it be resolved ?
Sub DeletePages()
Dim WordApp As Word.Application
Dim myDoc As Word.Document
' Open the Word document
Set WordApp = New Word.Application
Set myDoc = WordApp.Documents.Open("C:\mydocument.docx")
' Delete pages 3 to 5
myDoc.Range(Start:=myDoc.Bookmarks("Page3").Range.Start, _
End:=myDoc.Bookmarks("Page5").Range.End).Delete
'Unbind
Set WordApp = Nothing
End Sub
For example:
Sub Demo()
Dim wdApp As New Word.Application, wdDoc As Word.Document, i As Long
With wdApp
.Visible = False
.DisplayAlerts = wdAlertsNone
Set wdDoc = .Documents.Open(FileName:="C:\mydocument.docx", AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
With wdDoc
For i = .ComputeStatistics(wdStatisticPages) To 1 Step -1
Select Case i
Case 5 To 10, 12 To 16
.Range.GoTo(What:=wdGoToPage, Name:=i).GoTo(What:=wdGoToBookmark, Name:="\page").Delete
End Select
Next
.Close SaveChanges:=True
End With
.DisplayAlerts = wdAlertsAll
.Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
To understand why you don't need to create any bookmarks - and to understand what the code is doing - see:
https://learn.microsoft.com/en-us/office/vba/word/concepts/miscellaneous/predefined-bookmarks
I am trying to copy a table from excel to word and then back again to excel using VBA. I have a script to do both of those things but how can I make the copy from word back to excel from the active word file that got created with "Copy2word" so that I dont have to specify the location of the word document in "Copy2excel"?
Sub Copy2word()
Dim wdApp As Object
Dim wdDoc As Object
Dim wkSht As Worksheet
'\\ Stay on any sheet from which you want to copy data
Set wkSht = ActiveSheet
wkSht.UsedRange.Copy
'\\ Start word and create new document to paste data
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
End If
Set wdDoc = wdApp.Documents.Add
'\\ Paste Data from Excel
wdDoc.Range.PasteExcelTable False, False, True
'\\ Stop Excel's cut copy mode
Application.CutCopyMode = False
MsgBox "Copy to Word Finished!", vbInformation, "Copy to Word"
End Sub
Sub Copy2excel()
Const DOC_PATH As String = "C:\Users\MASS\Desktop\Test\TK1.docx"
Dim sht As Worksheet
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
Dim i As Long, r As Long, c As Long
Dim rng As Range, t As Word.Table
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
Set WordDoc = WordApp.Documents.Open(DOC_PATH, ReadOnly:=True)
Set sht = Sheets("Sheet4")
Set rng = sht.Range("A20")
sht.Activate
For Each t In WordDoc.Tables
t.Range.Copy
rng.Select
rng.Parent.PasteSpecial Format:="Text", Link:=False, _
DisplayAsIcon:=False
With rng.Resize(t.Rows.Count, t.Columns.Count)
.Cells.UnMerge
.Cells.ColumnWidth = 14
.Cells.RowHeight = 14
.Cells.Font.Size = 10
End With
Set rng = rng.Offset(t.Rows.Count + 2, 0)
Next t
WordDoc.Close
WordApp.Quit
End Sub
I'm trying to copy a content from excel into a bookmark in MS word. But I'm getting run time error 424. Kindly help me with it. I'm very new to Visual basics and programming as well. I have attached my code.
Thanks
Sub WordDoc()
Dim wrdApp As Object
Dim Number As String
Dim wrdDoc As Object
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("H:\IP Automation\createDoc.docx")
Number = Worksheets("Sheet1").Range("A2")
Call InsBookmark(ID, Number)
End Sub
Sub InsBookmark(strBMName, strVariable)
If strVariable <> "" Then
If ActiveDocument.Bookmarks.Exists(ID) Then
ActiveDocument.Bookmarks(ID).Select
Selection.Delete
Selection.InsertAfter (strVariable)
End If
End If
End Sub
You shouldn't seperate this into two subs, as the word doc will not persist across them so "ActiveDocument" wont work. just copy the code from the second sub into the first and replace ActiveDocument with wrdDoc
This should work for you. Give it a go and see how you get along.
Sub Export_Table_Word()
'Name of the existing Word doc.
Const stWordReport As String = "Final Report.docx"
'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
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("PwC Contact Information")
Set rnReport = wsSheet.Range("Table1")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").Range
Dim tbl As Table
For Each tbl In wdDoc.Tables
tbl.Delete
Next tbl
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'Turn off screen updating.
Application.ScreenUpdating = False
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
'Quit Word.
wdApp.Quit
'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox "The report has successfully been " & vbNewLine & _
"transferred to " & stWordReport, vbInformation
End Sub
I have an excel file that generates some graphics, and I am trying to create a report in Word that pulls some of these graphics. I have everything set up and working, but the Word file isn't generated unless Word is already open. This is a snippet of what I have so far - what am I missing?
Sub Generate_Report()
Dim wordApp As Object
Dim templateFile As Object
On Error Resume Next
' Define template word file
Set wordApp = GetObject(, "Word.Application") 'gives error 429 if Word is not open
If Err = 429 Then
Set wordApp = CreateObject("Word.Application") 'creates a Word application
' wordapp.Documents.Open ThisWorkbook.Path & "\WeatherShift_Report_Template.docm"
wordApp.Visible = True
Err.Clear
End If
Set templateFile = wordApp.Documents.Add(template:=ThisWorkbook.Path & "\WeatherShift_Report_Template.docm")
' Copy charts to new word file
Sheets("Dashboard").Select
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.ChartArea.Copy
With templateFile.Bookmarks
.Item("dbT_dist_line").Range.Paste
End With
Your On Error Resume Next may be masking a later error.
Try this:
Sub Generate_Report()
Dim wordApp As Object
Dim templateFile As Object
On Error Resume Next
Set wordApp = GetObject(, "Word.Application") 'gives error 429 if Word is not open
On Error Goto 0 'stop ignoring errors
If wordApp Is Nothing Then
Set wordApp = CreateObject("Word.Application") 'creates a Word application
End If
wordApp.Visible = True '<< edit
Set templateFile = wordApp.Documents.Add(template:=ThisWorkbook.Path _
& "\WeatherShift_Report_Template.docm")
' Copy charts to new word file
Sheets("Dashboard").Select
ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.ChartArea.Copy
With templateFile.Bookmarks
.Item("dbT_dist_line").Range.Paste
End With
End Sub
I need to have a vb code in ms word 2003 that copy a a specific cell in excel file and paste it in word (filed). Below is what I have done and it result in error.
Sub cmdGetNumber()
Dim XL As Object
Dim WBEx As Object
Dim ExelWS As Object
Dim appwd As Object
Dim wdApp As Word.Application
''''
'On Error GoTo OLE_ERROR
Set XL = CreateObject("Excel.Application")
Set wdApp = CreateObject("Word.Application")
'Open Excel document
Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
Set ExelWS = WBEx.Worksheets("Sheet1")
XL.Visible = True
'appwd.Visible = True
ExelWS.Range("c2").Select
'Selection.Copy
'wdApp.Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteMetafilePicture
'wdApp.Documents.Save
Set wdApp = Nothing
Set ExelWS = Nothing
Set WBEx = Nothing
End Sub
Since this macro is in Word, you don't need to explicitly open a word instance. You can just do Documents.Add to add a new document, or Documents.Open to open an existing one.
Try this:
Sub cmdGetNumber()
Dim XL As Object
Dim WBEx As Object
Dim ExelWS As Object
Dim wdDoc As Word.Document
'On Error GoTo OLE_ERROR
Set XL = CreateObject("Excel.Application")
'Open Excel document
Set WBEx = XL.Workbooks.Open("C:\Documents and Settings\121567\Desktop\tafket1.xls")
Set ExelWS = WBEx.Worksheets("Sheet1")
'XL.Visible = True
ExelWS.Range("C2").Copy
Set wdDoc = Documents.Add
wdDoc.Activate
wdDoc.Select
Selection.Paste
WBEx.Close
XL.Quit
Set WBEx = Nothing
Set ExelWS = Nothing
Set XL = Nothing
End Sub
The above code will open your excel file, copy the cell C2, then open a new word document, and paste it there.
I see you have mentioned a (filed) in your question. Did you mean a Field or a File? If it is a Field then you may want to replace Selection.Paste with the relevant field name