Issue with extra space added before file insertion using InsertFile method - vba

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

Related

How to modify title text and keep auto numbering - VBA, word

In MS Word (2010 .docx) file I need to modify text of title with autonumber, but keep the autonumber:
Original Word Example:
1.4.12 [ORIGINAL_TEXT]
Intended tile after modification:
1.4.12 [MODIFIED_TEXT]
I can get the [ORIGINAL_TEXT] by
ActiveDocument.Paragraphs(i).Range.Text
This returns [ORIGINAL_TEXT], but not autonumber.
But by setting
ActiveDocument.Paragraphs(i).Range.Text = "[MODIFIED_TEXT]"
the autonumber disappear and the title text is only
[MODIFIED_TEXT]
(autonumber missing)
From there I understand, that assigning anything to ActiveDocument.Paragraphs(i).Range.Text is not a way, because I want to keep autonumber.
I was able to modify the title by
ActiveDocument.Paragraphs(i).Range.InsertBefore ("[MODIFIED_TEXT]")
This results in title in form:
1.4.12 [MODIFIED_TEXT][ORIGINAL_TEXT]
(This looks like pointless, but actually my [ORIGINAL_TEXT] is constant text in whole document - it is placeholder, which tells mactro where to insert autogenerated text "[MODIFIED_TEXT]". Therefore after inserting autogenerated text by InsertBefore I can later simply do find and replace "[ORIGINAL_text]" to "", but I want to avoid this second step)
How it is possible to replace [ORIGINAL_TEXT] by [MODIFIED_TEXT] without loosing the autonumber?
ActiveDocument.Paragraphs(i).Range.Text includes the paragraph mark (carriage return).
To replace the text you can either include a carriage return in your replacement text
ActiveDocument.Paragraphs(i).Range.Text = "[MODIFIED_TEXT]" & vbCr
or modify the range you are replacing
Dim textRange As Range
Set textRange = ActiveDocument.Paragraphs(i).Range
textRange.MoveEnd wdCharacter, -1
textRange.text = "Modified text"
The autonumber is likely in the paragraph formatting so you would want to avoid replacing the paragraph mark unless you can add that formatting back.

In MS-Word how do you VBA split a table inserting a Section Break AND a paragraph mark

wdSectionBreakNextPage does not come with a trailing paragraph mark
I have a massive table i copy from excel to word sprinkled throughout with homemade fields PAGEX and SECTIONX. My macro will change these to page and section breaks, splitting the table for each (what I want). But page breaks come with a trailing paragraph mark before the table and section breaks do not. My feeble attempts to insert a paragraph mark after a section break always ends up with the paragraph mark inside the table.
My goal is to get the same gap between my header and the beginning of the table after both section breaks and page breaks. I think I simply want a macro to insert a paragraph mark after my section breaks similar to the way wdPageBreak works (i.e., between the break and the table). But I'm open to suggestions.
As perhaps further clarification, doing this manually involves creating a new row after a section break, then converting that row to text (quite impractical for the counts I'm looking at).
Do While .Execute
Selection.Delete
Selection.InsertBreak Type:=wdSectionBreakNextPage
Loop
Try:
ActiveDocument.Compatibility(wdSplitPgBreakAndParaMark) = False
thanks free and macro. i probably should have noted that i'm a vba novice (cut-and-paste mostly).
i decided it was easiest to just insert a page break after each section break, and then do a replace of ^m^p by ^p.
this works in my case, but won't work for others reading this if they have existing page breaks they don't want to lose.
GJ

VBA to copy text from excel to on specific location in wordfile

Problem: Pasting copied data from excel to specific location in a word file.
Currently I have code which can paste the value, but it does so to "paragraph1"
myDoc.Paragraphs(1).Range.Paste
How do I specify the exact location (by line) in which to paste the data?
Let me know if more info is required.
Thanks!
Mohd Akhtar
Word gives a number to each character in the document's body, from 1 up. It then defines a range with Range.Start to Range.End So, Paragraphs(1).Range might be equal to Range(Start:=1, End:=120).
The text contained in that range is Range.Text, Read/Write. Therefore, Paragraphs(1).Range.Text = "My new paragraph text" will replace the existing text in the document's first paragraph. ActiveDocument.Range(0, 0).Text specifies the range before the first character in the document.
In order to insert text at a specific location you have to find the location, meaning the Range. As you have seen above, if the range has a length of 0 you can insert before or between existing text, and if it has any length the new text will replace whatever was there before. New and old text need not have the same length.
Counting paragraphs is helpful to find a range. You can also count words or sentences. You can search for a specific word combination. Or you can use a bookmark. In all of these cases you define a range the text of which you can replace outright, or which you can use to find a location relative to it where to insert the text, such as the beginning or end or after the 3rd word or whatever.
You could also use some bookmarks:
You can choose where you put your bookmark and then write on it like this
ThisDocument.Bookmarks("NAME_OF_THE_BOOKMARK").Range.Text = THE_EXCEL_DATA
To place a bookmark you have to click on the selected area and then go on Insert->Bookmarks and then name it.

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.