Delete page in Word - vba

I need VBA code to delete all sections(pages) except first in Word document
For this I use below code.
For Each oSec In ActiveDocument.Sections
If oSec.Index <> 1 Then
oSec.Range.Delete
End If
Next oSec
This works but does not delete second section only removes its content.
If I removes if condition in code it removes content of first page.
I want to preserve content of first page.
Please tell me where I am making mistake.

When deleting you need to include section break marks. Try to change this line:
oSec.Range.Delete
into this one:
ActiveDocument.Range(oSec.Range.Start - 1, oSec.Range.End).Delete
BTW, you should not think that page=section, they are different type of document units.

Related

Issue with extra space added before file insertion using InsertFile method

I am having an issue when inserting a file into a word document(main document) using the InsertFile method using a Word VBA Macro I created, where it is inserting an extra space to the left of the paragraph I am trying to insert into the document. The document I amd trying to insert into is set up with multiple bookmarks that either deletes or retains paragraphs and is supposed to retain the spacing between the paragraphs. For whatever reason When inserting a file it adds not only that extra space but also adds extra lines after the paragraph too. Just so you know I have space symbols enabled which word represents with dots.
Below is the structure of the main document that I am inserting all of the text into (I scratched out text from a paragraph that is always in the main document, anonymized the text):
The reason why the middle paragraph bookmark isn't set to the same line as the previous paragraph is because when I try to insert a line break before inserting the file it doesn't add the line breaks and just prints the text in the previous paragraph when i really want them seperated. Wierd thing is the line breaks work for the other paragraphs that are not inserting text from a file...
The file I am attempting to insert is just a word document which consists of one paragraph of text where the space before the first word of the paragraph is not present but when inserted that space is added. Here is an image of the issue with the main document after all of the insertions(anonymized the text with explanations of the issue):
My code first sets the bookmark to a range variable, then sets the text of the bookmark to blank(essentially deleting the bookmark), then uses that range variable to insert either a file, hardcoded text or a database field. The code works fine for the text or database field but adds that extra space when inserting text from a file. Here is the code I am using to insert the file into my main document:
BookmarkRange.InsertFile (FiletoInsert)
My question is there a way to avoid this extra space? Or if not do I just need to figure out the range for that extra space and then delete it out after the insertion? Let me know if you need more information to answer this question.
I can't duplicate the space you're seeing when you insert a file, unless that file has a space as its first character.
When you insert a file, the last character inserted will be a paragraph mark, which explains why the text following what you insert "moves down". If you're getting more than one new paragraph then the file you're inserting contains multiple "empty" paragraphs at the end.
There are two possibilities for bringing in the file and suppressing that paragraph mark:
Bookmark the text in the file that you want to bring in. InsertFile has a parameter Range that lets you specify a bookmark name in the file and inserts only the bookmark's content:
rngBookmark.InsertFile "C:\Test\Test_Centered.docx", "test3"
Remove the paragraph after inserting the file. Range.InsertFile leaves the range at its starting point. So a second range is needed to mark the point that follows the inserted content.
Sub InsertFileNoLeadingSpace()
Dim rngBookmark As Word.Range, rngAfterBookmark As Word.Range
Set rngBookmark = ActiveDocument.Bookmarks("test1").Range
Set rngAfterBookmark = rngBookmark.Duplicate
rngAfterBookmark.Collapse wdCollapseEnd
'Move one character further so that the Range is beyond the inserted content
rngAfterBookmark.MoveStart wdCharacter, 1
rngBookmark.InsertFile "C:\Test\Test_Centered.docx"
'Move it back by two in order to pick up the inserted paragraph mark
rngAfterBookmark.MoveEnd wdCharacter, -2
'If the position after the inserted content is required after deleting the paragraph mark
'this next line is necessary because deleting the paragraph mark
'sets rngAfterBookmark to another location - it doesn't remain where you'd think
Set rngBookmark = rngAfterBookmark.Duplicate
rngAfterBookmark.Delete
rngBookmark.Select
End Sub

Word 2010 VBA: add text to template without deleting everything below

I have been writing a code to build a custom document for weekly reporting. I had it set to create a new doc, build the tables, format everything, insert a logo, etc., and I hit a wall when Word crashed every time I tried to resize the logo through VBA. It then occurred to me that I was doing this the wrong way anyway, and that I should build a template, have the code open that template, and then insert the changes directly into that document.
When I add text to the range I need, everything below is deleted. I have three lines of a header; the third line is variable and will change each week. Below that I have three tables, some cells of which will be updated each week. Right now I am just stuck at the third line of the document.
Here is an example of what I have. It is extremely short because I started anew and hit a dead end immediately.
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46)
InsertSpot.Text = "Hello"
When I run that, everything is deleted below "Hello".
I tried some different things, such as:
Set InsertSpot = Template.Range(46,50)
InsertSpot.InsertAfter "Hello"
That doesn't work; it just adds "Hello" to the first cell of the first table.
I feel silly being stuck at such an elementary part, but I honestly have no idea what to do here. Everything I looked at online talked about how to insert text at a bookmark without deleting the bookmark. I just want to enter text, period.
Any thoughts?
I found the answer. I did the following:
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46, 46)
InsertSpot.Text = "Hello"
I had to list both the starting AND the ending character so that the inserted text would not bleed over into the rest of the page. Hope I helped someone else who is having a similar problem. Unfortunately Word VBA is pretty lacking in support and clear explanations.
other alternatives can be
ThisDocument.Range(46).InsertBefore "Hello"
ThisDocument.Tables(1).Range.InsertBefore "Hello"
ThisDocument.Paragraphs(3).Range.InsertAfter "Hello"

vba macro for word : delete sub section

I have sub sections in a word document which I want to delete based on user inputs in a custom user interface.
For e.g : I want to delete sub section 3.1.1 under the section 3
I used the following code, but it deletes the entire section but I want to delete only a specific sub section:
ActiveDocument.Sections(x).Range.Delete
Here I am not able to give x = 3.1.1, it only accepts just the integer value like 3 and that deletes the entire section.
Word doesn't have nested sections, so you probably need to cycle through the sections until you find one that matches your needs. So, let's say you have a Word document that looks like this:
Title___[continuous section break]
Stuff
Section 1___[continuous section break]
Stuff
Section 1.1___[continuous section break]
Stuff
You could loop through the sections and check the first paragraph of each:
For each objSect in ActiveDocument.sections
if trim(replace(objSect.Range.Paragraphs.First.range.Text, chr(13), "")) like "* 1.1" then objSect.range.delete
Next objSect
Of course, that means if you want to delete section 1 you'll need to delete it along with any sub-sections, one at a time.
If what you really want is something like what the navigation pane gives you, I don't know if that's supported in VBA. There don't appear to be any methods that would mimic the Navigation Pane Delete option.

Remove first line from Word Document process it and put a new line at the beginning of the document

I am developing an application wherein I need to delete the first line of several word documents, merge them, merge their tables into one and place it at the top, remove all the individual tables which are merged, and then giving the merged table a name.
I am through with almost everything except removing the first line of the individual word documents (which will be merged into one) and Putting name string to the newly generated table in the new document on top of the table. The newly generated table will be placed at the top of the new document (which is result of merging of all other documents).
Can someone suggest a way to do it. If possible, deletion of first two lines will help more.
Removing first line could mean removing first paragraph or just first line as you could see it. They are not the same therefore I provide both solution below
'Remark: for ActiveDocument
'removing first paragraph
ActiveDocument.Paragraphs(1).Range.Delete
'removing first line
ActiveDocument.Range(0, 0).Select
Selection.MoveEnd wdLine
Selection.Delete

automating word 2010 to generate docs

the webapp was already done on office2007 and i need to convert it so it'll work in office2010.
i was able to convert the header generator part of the code but i have problem with the body of the doc itself. the code copy the data from a "data" doc and paste it into the generated doc.
appword.activewindow.activepane.view.seekview = 0
'set appsel1 = appword.activewindow.selection
set appsel1 = appword.window(filepath).selection -that is the original one
appdoc1.bookmarks("b1").select
appword.selection.insertafter("some text")
appsel1.endkey(6) -the code stops here
appword.selection.insertafter("some other text")
the iexplorer debuger says ERROR:appsel1 object required. and when i view its data using the iexplorer debugger its data is "empty" instead of "{...}"
can anyone tell me what i'm doing wrong
if you need more of the code tell me.
From MSDN
After this method is applied, the selection expands to include the new
text.
If you use this method with a selection that refers to an entire
paragraph, the text is inserted after the ending paragraph mark (the
text will appear at the beginning of the next paragraph). To insert
text at the end of a paragraph, determine the ending point and
subtract 1 from this location (the paragraph mark is one character).
However, if the selection ends with a paragraph mark that also happens
to be the end of the document, Microsoft Word inserts the text before
the final paragraph mark rather than creating a new paragraph at the
end of the document.
Also, if the selection is a bookmark, Word inserts the specified
text but does not extend the selection or the bookmark to include the
new text.
So I suspect that you still have no selected text.
I wonder if you can do a Selection Collapse(wdCollapseStart) but that's just a thought.