automating word 2010 to generate docs - automation

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.

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

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.

Convert automatic numbering and bullets to plain text

I have a word document with automatic numbering and bulleting.
I have selected the text where I need to convert automating numbering and/or bulleting to normal text.
In addition I need to keep both the formatting and numbers/bullets of the selected text.
What I have already tried:
cut the paragraphs and special pasted them (but it breaks formatting);
unpressed the "numbering"/"bulleting" button (but it erases all numbers and bullets);
used VBA-macro (but it returns an error):
Code (error, method or data member not found):
Sub convertNumbersAndBulletsToText()
Selection.ConvertNumbersToText
End Sub
What would you recommend me to do in order to keep both formatting and numbers/bullets?
You have practically done everything yourself!
This code will work:
Sub convertNumbersAndBulletsToText()
Selection.Range.ListFormat.ConvertNumbersToText
End Sub
Your example returns error because ConvertNumbersToText method doesn't work with Selection. It works with Range!
(look here: Change selected automatic numbered list to plain text in word)
Beware!
If you want to carry out many changes, you may find it easier to make them with ActiveDocument (look below).
But if want to do it manually (or through a loop),
then you'd better loop from the last element you want to convert till the first one
(not vice versa, because auto-numbers would then increment by one all the time)!
Small Tips
Personally I would recommend you to use this code instead:
Sub convertNumbersAndBulletsToText()
Dim myRange As Range
Set myRange = Selection.Range
myRange.ListFormat.ConvertNumbersToText
End Sub
Why this one? It is a little bit more flexible! Instead of Selection.Range you could use any other type of Range (ActiveDocument, ActiveDocument.Paragraphs, myRange.SetRange etc)
Here are some links from msdn to give you basic examples of Ranges: 1) Range Object (Word) (msdn), 2)
Range.SetRange Method (Word) (msdn).
Just for your information, you don't need to save VBA if you don't want to. You can use Immediate Window to launch VBA.
Press alt+f11 (VBA-editor), then ctrl+g (Immediate Window).
Paste the code bellow, press enter.
VoilĂ !
Code (for Immediate Window):
ActiveDocument.ConvertNumbersToText
(It converts auto-numbers and auto-bullets to normal numbers and bullets everywhere in ActiveDocument).
The result of any VBA here would be number+tab+text. If you want to have number+space+text you can:
either at the very end replace (press ctrl+h) this one .^t (dot and tab) for . (dot and whitespace),
or at the very beginning 1) select the list, 2) right click on it, 3) click "Adjuct list idents", 4) click "Follow number with: Space". (Look here: Adjust the spacing for a single list item (support.office))
You may need to have a leading zero in (auto-)numbering, then you can press ctrl+f9, write SEQ MyList \# "000" inside curly brackets, press alt+f9 to finish (look here: Insert fields in Word (support.office)). But this goes beyond the question, though you may find word fields really useful in some cases.
To sum up:
You can replace both bullets and numbers for plain text in Word:
for Selection (look above);
for ActiveDocument (look above);
with a Range (examples in msdn);
with a loop (examples are welcomed). But bear in mind that you are to loop from the end of the document to the beginning.

Make Word's automatic spell-checking pick up dictionary changes

In MS Word it's possible to add words to a custom dictionary so they're recognized. If a word is not recognized, Word automatically puts a red squiggly line underneath it. If you add that word to the custom dictionary, this line disappears. What I'd like to do is perform this process automatically via a macro. It appears that one has to manually open the dictionary file and write the new word, as there is no method on the Word Dictionary object to add words to a given dictionary. This is no problem, except that Word doesn't automatically pick up the new word and remove the red squiggly lines underneath the newly-added word. I've even tried clearing the custom dictionaries and adding them back in, but it doesn't seem to reload the dictionary until you manually run a spell check. Sample code for this follows:
Dim x As Dictionary
Dim fname As String
fname = "C:\Users\me\AppData\Roaming\Microsoft\UProof\md.dic"
' code to add word to dictionary goes here
With CustomDictionaries
.ClearAll
.Add fname
.ActiveCustomDictionary = CustomDictionaries.Item(fname)
End With
Is there any way to make Word recognize the newly added word(s) in a custom dictionary without running the interactive spell check? It does this silently if you manually add words, but I can't seem to replicate this behavior in VBA. I'd like the red lines to go away automatically just like they do when you manually add words.
I haven't exactly solved the problem, but I think I figured out a work around. You can get a collection of Range objects which represent spelling errors using ActiveDocument.SpellingErrors. I'm going to search this collection for text matching the word I've added to the dictionary, and then set .NoProofing = True on the object. This appears to make the red lines go away, and having added the new word to the dictionary will prevent them from coming back the next time I open the document. I haven't fully tested this approach, but it looks promising.
EDIT
This approach is flawed, as additional instances of the word which are entered during the same session will have the red squigglies underneath them because they haven't been explicitly ignored and the spell check isn't yet using the updated dictionary. If you just pull up the custom dictionary dialog manually and click OK, something happens in the background to re-read the dictionary. I just can't figure out how to do this in code.

Using VBA in MS Word 2007 to define page elements?

I'd like to be able to create a page element which I can feed text and it will form itself into the preferred layout. For instance:
{MACRO DocumentIntro("Introduction to Business Studies", "FP015", "Teachers' Guide")}
with that as a field, the output should be a line, the first two strings a certain size and font, centred, another line and then the third string fonted, sized and centred.
I know that's sort of TeX-like and perhaps beyond the scope of VBA, but if anyone's got any idea how it might be possible, please tell!
EDIT:
Ok, if I put the required information into Keyword, as part of the document properties, with some kind of unique separator, then that gets that info in, and the info will be unique to each document. Next one puts a bookmark where the stuff is going to be displayed. Then one creates an AutoOpen macro that goes to that bookmark, pulls the relevants out of the keywords, and forms the text appropriately into the bookmark's .Selection.
Is that feasible?
You're certainly on the right track here for a coding solution. However, there is a simpler way with no code - this is the type of scenario that Content Controls in Word 2007 were built for and with Fields/Properties, you can bind to content controls (CC). These CC can hold styles (like centered, bold, etc.). No VBA required.
The very easiest thing to do is to pick 3 built-in document properties that you will always want these to be. For example, "Title" could be your first string, "Subject" your second string and "Keywords" your third. Then, just go to the Insert ribbon, Quick Parts, Document Properties and insert, place and format those how you like. Then go to Word's start button (the orb thingy) and then under Prepare choose Properties. Here you can type, for example "Introduction to Business Studies", into the Title box and then just deselect it somehow (like click in another box). The Content Control for Title will be filled in automatically with your text.
If you want to use this for multiple files, just create this file as a .dotx (after CC insertion/placement/formatting and before updating the Document Properties' text). Then every time all you'll have to do is set these three properties with each new file.
Well, yes, it did turn out to be feasible.
Sub autoopen()
Dim sKeywords As String
sKeywords = ActiveDocument.BuiltInDocumentProperties(4)
ActiveDocument.Bookmarks("foo").Select
Selection.Text = sKeywords
End Sub
Okay, I have some filling out to do, but at least the guts of it are there.