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
Related
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
I am a total VBA novice, but I've managed to cobble together some code which allows me to export an excel 2010 chart into a new Word 2010 document. The only problem I have is that I would like to unlink the chart from excel once it is exported, so that it doesn't change when excel is updated. I've looked everywhere, but nothing seems to work.
The only other code which seems to fit the bill takes the chart and saves it as an image prior to pasting it, but this would not work as I have nowhere to save the image - users in our organisation do not have access to the C:\ drive, and without knowing everyone's user details, I cannot write code which will do the job.
The code I've written so far is this, which does work, but does not unlink:
Sub Copy_Paste_Report_1_Graph_to_new_word_document()
'
'Copy/Paste An Excel Chart Into a New Word Document
'(VBE > Tools > References > Microsoft Word 12.0 Object Library)
'Excel Objects
Dim ChartObj As ChartObject
'Word Objects
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Copy Chart from Excel
Set ChartObj = Worksheets("External Dashboard").ChartObjects("Chart 1")
'Create an Instance of MS Word
On Error Resume Next
'Is MS Word already opened?
Set WordApp = GetObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
'If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate
'Create a New Document
Set myDoc = WordApp.Documents.Add
'Copy Excel Chart
ChartObj.Copy
'Paste Chart into MS Word
myDoc.Paragraphs(1).Range.PasteSpecial Link:=False _
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
I've probably included more than I need to, but like I said, I'm a novice.
Use .CopyPicture and .PasteSpecial methods:
Sub Copy_Paste_Report_1_Graph_to_new_word_document()
Dim ChartObj As ChartObject
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Set ChartObj = Worksheets("External Dashboard").ChartObjects("Chart 1")
Set WordApp = CreateObject(class:="Word.Application")
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Add
ChartObj.CopyPicture xlScreen, xlPicture
myDoc.Paragraphs(1).Range.PasteSpecial
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 wrote below code to take screenshot form Excel document and paste on word document.It works fine However I am unable to convert This Word document into PDF and error displays"Object does not support this property or method".It seems that i defined Variable (Objword as variant) not correct.Please any one can help.
Sub CopyToWordPicture()
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim objword As variant
Set objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open "C:\Automation\BH Report\Daily&BH RAN KPI report_ok.docx"
Workbooks.Open Filename:="C:\Automation\BH Report\Daily_Hourly KPI Template.xlsx"
Sheets("BH_Graphs").Select
Range("A1:k50").CopyPicture xlPrinter
With objword
'.Documents.Add
.Selection.Paste
.Visible = True
End With
'WDApp.Visible = True
' WDApp.Selection.GoToNext wdGoToPage
Windows("Daily_Hourly KPI Template.xlsx").Activate
Sheets("Daily_Graphs").Select
Range("A1:J50").CopyPicture xlPrinter
With objword
'.Documents.Add
.Selection.Paste
.Visible = True
End With
'export as PDF
objword.ExportAsFixedFormat OutputFileName:="C:\Automation\BH Report\Daily&BH RAN KPI report.pdf", _
ExportFormat:=wdExportFormatPDF
end sub
I'm trying to create a report that analyzes multiple word documents in a folder and analyzes checkboxes in the document to determine if a set of tests passed or failed. I have code that loops through all documents in a folder, but I'm having a hard time determining how to determine if the boxes are checked.
The first checkbox I'm trying to evaluate is tagged "PassCheckBox". I've found several articles with syntax on how to do this, but none seem to work with the way I'm iterating through the word files. My current code give me "Object is Required" when I try to run.
Here is my current code:
Sub ParseTestFiles()
Dim FSO As Object
Dim fPath As String
Dim myFolder, myFile
Dim wdApp As Object
Dim PassValue As Boolean
fPath = ActiveWorkbook.Path
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = FSO.GetFolder(fPath).Files
For Each myFile In myFolder
If LCase(myFile) Like "*.doc" _
Or LCase(myFile) Like "*.docx" Or LCase(myFile) Like "*.docm" Then
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word not yet running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
' Here is where I'm having an issue
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked
Set wdApp = Nothing
End If 'LCase
Next myFile
End Sub
Try to use:
Dim c, wdDoc
Set wdDoc = wdApp.Documents.Open(CStr(myFile))
wdApp.Visible = True
For Each c In wdDoc.ContentControls
If c.Title = "PassCheckBox" Then
PassValue = c.Checked
Exit For
End If
Next
instead
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked