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

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.

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.

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 VBA search for adjacent (non-space) characters with different formatting

I need to be able to find every place in my document (hundreds of pages) where there is a formatting change without a space. For example:
a bold partnext to regular text
Or red text next to black with no space. I want to have my macro find each "word" (in the vba sense) like this, and execute code based on that character location accordingly. (The loop should identify the character position where the format change occurs... although I can do that part with a loop through the characters within the found word).
Is there a simpler way to do this than by looping character by character through the whole document and checking for a difference in formatting, which would be too resource-intensive?
Thanks for your help.

VBA for changing font and colour of a cell if a certain word is typed in it

I have a somewhat large spreadsheet with a type of summary page that follows a calender layout.
On this page I manually change the font and color of cells to make it easy for me to find certain things on it. For example, (I lecture mathematics) if I have revision on a certain lesson, I make that cell bold and green. (exact type of green I can sort out myself). I want a VBA code if possible so that if I type the word revision into a cell on that sheet only, not whole workbook, that it would automatically change it to green.
Realistically, I don't manually type in the word revision always. Some of it uses lookups of various types to find what happens on that day to display a word (for example revision) in that given cell.
I don't know if this is possible to do. I realize that if "revision" is shown due to a lookup then the contents of that cell is not equal to "revision" but a formula which simply displays "revision"
Any assistance would be appreciated. If I have a basic code I can manipulate to get it right.
Thanks
Maybe you're looking for something along the lines of:
Sub CheckRevision()
Dim CurCell As Object
For Each CurCell In ActiveWorkbook.ActiveSheet.Range("A1:AZ500")
If CurCell.Value = "Revision" Then CurCell.Interior.Color = RGB(0,204,0)
Next
End Sub
Or equivalently, you can probably use conditional formatting. Home Tab > Conditional Formatting > Highlight Cells Rules > Text that Contains. From there, type the value "Revision" into the value box and you can change the format of the cell to how you like it.

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.