PDA

View Full Version : Solved: Word.application help



Mr Doubtfire
04-18-2005, 06:06 AM
I am a new comer and I have the following questions when developing a Word.application object under VB6.
I would like to change the font and alignment for different lines. Could anyone show me how to do it? I understand there is range and paragraph, and "insertbefore" and "insertafter". I DID try and it is NOT working as what expected.
eg.
Line1 (current date) font 12 bold alignment right
Line2 (customer name) font 12 alignment left
Line3 (reference) font 14 bold alignment center
line4 (variable1) font 12 alignment left (variable2) font 12 alignment right
line5 (variable3) font 12 alignment left (variable4) font 12 alignment right

Thank for the help in advance.:friends:

Killian
04-18-2005, 06:39 AM
Hi and welcome to VBAX :hi:

The Word object model is pretty much centred around the 'Range' object. A 'Range' being any defined contiguous area of the document i.e. the first five characters, the whole content, paragraphs, 6 to 14, the current selection etc, etc.
The Range object is the one that has all the useful methods and properties, like .Font.Bold = True

The Paragraphs collection is made up of all the paragraph objects in a document (or in a selection or defined range).

Referring to one of the paragraph objects by index and using it's range property will refer to to range of that paragraph, so to change the fontsize of paragraph three, use:ActiveDocument.Paragraphs(3).Range.Font.Size = 14
In your example, if each of those lines os a seperate paragraph at the stahrt of the document, the following code would format it as specified:With ActiveDocument.Paragraphs(1)
.Range.Font.Size = 12
.Range.Font.Bold = True
.Alignment = wdAlignParagraphRight
End With
With ActiveDocument.Paragraphs(2)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphLeft
End With
With ActiveDocument.Paragraphs(3)
.Range.Font.Size = 14
.Range.Font.Bold = True
.Alignment = wdAlignParagraphCenter
End With
With ActiveDocument.Paragraphs(4)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With
With ActiveDocument.Paragraphs(5)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With

Mr Doubtfire
04-18-2005, 06:53 AM
Killian,


You are killing me with a fast, detailed and warm reply.
Thanks and I would test it and see I need more help and decide whether to have the "beerchug"!
Have a good day!:thumb

TheAntiGates
04-18-2005, 09:49 AM
If I may jump in...is using Characters object acceptable?For i = Selection.Start To Selection.End
ActiveDocument.Characters(i).Font.Size = iNewSize
Next iI commented out this routine in NORMAL.DOT due to disastrous results on XL00 (or maybe XL02?). However I recall that that problem was with screwy values for selection.start and selection.end - in the VBA window the loop range did not correspond to what clearly was selected in the .DOC. (I don't seem to be able to reproduce the problem with XL03.)

(Hmmm - thinking out loud, maybe the Selection object formerly picked up the selection from the VBA code window, when examined while stepping through code?)

Anyway, is this snippet okay for modifying the Selection?

Killian
04-18-2005, 10:56 AM
It should work, but it would be massively less efficient and I don't see any advantage over applying the font size property to the selection object's range property Selection.Range.Font.Size = iNewSize
It's one line of code that runs significantly faster and uses less memory.
IMHO, understanding and getting the best use out of the Range object is key to successful Word VBA programming.

TheAntiGates
04-18-2005, 11:19 AM
Thanks - point well taken. But I will confess my hidden agenda in using Characters(), FYI. The actual code isFor i = Selection.Start To Selection.End
If ActiveDocument.Characters(i).Font.Size = iOldSize Then
ActiveDocument.Characters(i).Font.Size = iNewSize
end if
Next iI did this is to selectively replace some fonts while preserving others - for example, if 99% of a document is size 10 and I want to move it up to 12, but not disturb anything already explicitly set to something else, such as that crucial 24-point sentence that's right dead in the middle of the selection! So I'd pass 10 and 12 to the routine with this code.

But you didn't know that. :cool: In the absence of the conditional processing, I appreciate your point.

I'm all in favor of greater efficiency - the first thing that comes to mind is
dim ch as character, for each ch in selection, etc.
though since there's no such object as "Character" ... :bug:

Mr Doubtfire
04-18-2005, 12:22 PM
Killian,

Do I just need to insert my "lines" in between your corresponding "paragraphs"!?
Thanks!:help

TheAntiGates
04-18-2005, 12:36 PM
What he meant was if each one of your lines "WAS" (or "is") a paragraph, his code would take care of it. It was just a convenient way to make each of your "units" into a manageable yet distinct object. "Lines" as you have are well suited to become paragraphs by simply hitting the enter key after each line.

Killian
04-18-2005, 01:23 PM
Mr Doubtfire,
The code i posted replaces you lines, provided each of the lines ends with a return (vbLrf or paragraph mark) for para's 1 thru 5, which I imagine it does. But maybe your lines are seperated by a soft return or some-such which makes it more complicated!?

AntiGates,
You raise an interesting point with "for each ch in selection"
You can indeed do that. The character collection is what you want to iterate thru, and each object in it returns a range of each individual charater, so you were spot on, just define the ch as Range.Dim c As Range
Dim iOldSize As Integer, iNewSize As Integer

iOldSize = 10
iNewSize = 12
For Each c In Selection.Characters
If c.Font.Size = iOldSize Then
c.Font.Size = iNewSize
End If
NextYou'll see how much quicker that is! Collections are there to be iterated through. (Zack, if you're reading this, well... I think you know where I'm coming from :rotlaugh: )

But it would also be worth doing a comparison with (what I suspect many would call the "right" tool for the job) a find/replace structure that only considers the formatting (size)Dim iOldSize As Integer, iNewSize As Integer

iOldSize = 10
iNewSize = 12
With Selection.Range.Find
.ClearFormatting
.Font.Size = iOldSize
With .Replacement
.ClearFormatting
.Font.Size = iNewSize
End With
.Execute FindText:="", ReplaceWith:="", Format:=True, _
Replace:=wdReplaceAll
End With

TheAntiGates
04-18-2005, 01:38 PM
With Selection.Range.FindFreaking beautiful solution. My mind was up on the first half of your post but you warp-sped me way ahead!:bow:

Very nice - especially the .ClearFormatting on both sides. When I first saw it, I winced (for the obvious reason), but it's just perfect where you've applied it.
Thanks for your effort and attention to detail and quality! :beerchug:

Mr Doubtfire
04-18-2005, 01:59 PM
I apologize if my questions are too dumb.
My first two lines are as followed.

Line1 (current date) font 12 bold alignment right
Line2 (customer name) font 12 alignment left

The provided "paragraph"s would act just like a template for the "inserted" lines.
My question is/are how I could "insert"before/after and using which properties ? range/parapgraph or ...?
Thanks again.

With ActiveDocument.Paragraphs(1)
.Range.Font.Size = 12
.Range.Font.Bold = True
.Alignment = wdAlignParagraphRight
End With
With ActiveDocument.Paragraphs(2)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphLeft
End With

The project I have is to create Word docs through VB6 by retrieving data from a database.

Line1 (current date) font 12 bold alignment right
Line2 (customer name) font 12 alignment left
Line3 (reference) font 14 bold alignment center
line4 (variable1) font 12 alignment left (variable2) font 12 alignment right
line5 (variable3) font 12 alignment left (variable4) font 12 alignment right

The first line is current date, which is "Date:" & now()
The second line is our company name.
The third line is Reference (like regarding what matter)..
The fourth line is billing customer (shift left) and shipping customer (shift right).

All documents are created from scratch.
Hopefully it is clearer. Thank you.

Zack Barresse
04-18-2005, 02:53 PM
Mr. Doubtfire: some info for you I edited your post to include them, hope that is ok with you.

Killian
04-18-2005, 03:58 PM
Just changing the focus for a moment, you might want to read this (http://www.vbaexpress.com/forum/showthread.php?t=2770) thread as an alternative approach (there's an attachment on my post as a demo)
If you don't want to use that method, you can call the paragraph formatting code after the data is inserted.
Hopefully I'm not confusing the issue - I think if you have a look at the file on that thread you'll get what I mean.
If not post back and we'll get some code together :yes

Mr Doubtfire
04-18-2005, 07:05 PM
Dim objApp As Word.Application
Set objApp = New Word.Application
dim strToday
dim strCustomer
dim strReference
dim variable1

strToday = Date()
strCustomer = "Killian"
strReference = "Order notice"
variable1 = "blah blah"


With ActiveDocument.Paragraphs(1) 'This is where the error is for object missing
.Range.Font.Size = 12
.Range.Font.Bold = True
.Alignment = wdAlignParagraphRight
End With
With ActiveDocument.Paragraphs(2)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphLeft
End With
With ActiveDocument.Paragraphs(3)
.Range.Font.Size = 14
.Range.Font.Bold = True
.Alignment = wdAlignParagraphCenter
End With
With ActiveDocument.Paragraphs(4)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With
With ActiveDocument.Paragraphs(5)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With

ObjWord.Selection.TypeText Text:= strToday & vbCrLf
ObjWord.Selection.TypeText Text:=strCustomer & vbCrLf
ObjWord.Selection.TypeText Text:=strReference & vbCrLf
ObjWord.Selection.TypeText Text:="variable1" & vbCrLf


I ran it with object missing.
Please comment:help .Thanks.

geekgirlau
04-18-2005, 07:40 PM
Couple of things:

All of the Word commands you have entered need to refer to the Word Application object. VB doesn't have an "ActiveDocument" object, so that's why you're getting the error.
Your "Selection.TypeText" command was using a non-existent object variable "objWord". It's a good idea to make sure you type "Option Explicit" at the top of your module to make sure all variables are declared.
If you are setting the Word object variable as "New", you have to type the text in before you format the paragraphs. Otherwise any paragraph number greater than 1 doesn't exist yet!
Make sure you release the Word object variable at the end by setting it to "= Nothing".

Dim objApp As Word.Application
Dim strToday
Dim strCustomer
Dim strReference
Dim variable1

Set objApp = New Word.Application

strToday = Date
strCustomer = "Killian"
strReference = "Order notice"
variable1 = "blah blah"

With objApp
.Selection.TypeText Text:=strToday & vbCrLf
.Selection.TypeText Text:=strCustomer & vbCrLf
.Selection.TypeText Text:=strReference & vbCrLf
.Selection.TypeText Text:="variable1" & vbCrLf

With .ActiveDocument.Paragraphs(1) 'This is where the error is for object missing
.Range.Font.Size = 12
.Range.Font.Bold = True
.Alignment = wdAlignParagraphRight
End With
With .ActiveDocument.Paragraphs(2)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphLeft
End With
With .ActiveDocument.Paragraphs(3)
.Range.Font.Size = 14
.Range.Font.Bold = True
.Alignment = wdAlignParagraphCenter
End With
With .ActiveDocument.Paragraphs(4)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With
With .ActiveDocument.Paragraphs(5)
.Range.Font.Size = 12
.Range.Font.Bold = False
.Alignment = wdAlignParagraphRight
End With
End With

Set objApp = Nothing


Oops - you'll also need the following:

With objApp
.Documents.Add , , , True
.Visible = True

<rest of code>

Mr Doubtfire
04-19-2005, 06:23 AM
Thank you for ALL guys here for the help.
This is the site I should have joined a year ago.
I should still have questions.
First, how I could it "Saveas" "c:\test\doc1.doc"?
Second, how I could paste an image/picture (like logo) to the top front to every page (Word doc) and add a line feed after it to jump to the next line for text adding?
I have tried the .Visible = True, but it seems to show nothing at all.
Thanks ALL!:bow:

TheAntiGates
04-19-2005, 07:16 AM
how I could it "Saveas" "c:\test\doc1.doc"?Is there a KB on macro recorder here? Rather than restate what's probably done more elquently in a KB or article I'll pose that ... but in case there isn't one:

When you're not sure how to use VBA to accomplish a Word operation, but can manually accomplish it with the keyboard and mouse in the "regular" Word Window (such as with menu choices), you can have Word (or Excel or Powerpoint for that matter) "record a macro" and create code for you.
Click menu item tools/Macro/Record New Macro;
pick a name or accept its selected selection;
do the operation;
click menu item tools/Macro/Stop Recording;
open VBA (alt-F-11);
locate the code.
change the code to do what you REALLY want, vs. what it ASSUMED you wanted.
Bang on the help file to comprehend the syntax/see the "See alsos"/etc. for a new or unfamiliar command that recorder reveals to you.
Copy/paste the code elsewhere if appropriate.
Either (A) Go "Whew" if recorder revealed what you wanted, or (B) Go "#$%^!!" if recorder was no help.

Note that loops, variables, error handling and conditional statements are not created by the recorder; but it's useful to find out what VBA command does a certain operation. There's no shame in using macro recorder to "cheat for you" like this, regardless of your skill level.

Recommended: give suitable thought to using a dummy copy of your application file for experimental / learning purposes.

MOS MASTER
04-19-2005, 12:45 PM
I should still have questions.
Hi, :D

Please put you're questions that are different from the original topic in a separate topic. This will keep the forum readable for those who seek the same answer! :friends:



First, how I could it "Saveas" "c:\test\doc1.doc"?
objApp.ActiveDocument.SaveAs FileName:="c:\test\doc1.doc"



Second, how I could paste an image/picture (like logo) to the top front to every page (Word doc) and add a line feed after it to jump to the next line for text adding?
Many way's to code this.
This is one way...test first in normal Word document and later add to you're Office automation. (So include code for "objApp")

The code:
Sub PicsInHeaders()
Dim oSection As Word.Section
With Selection
.HomeKey Unit:=wdStory, Extend:=wdMove
With .PageSetup
.SectionStart = wdSectionContinuous
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
End With
End With

With ActiveDocument.Sections(1).Headers.Item(1).Range
.InlineShapes.AddPicture FileName:=ThisDocument.Path & "\Test.jpg"
.InsertAfter Text:=vbCrLf & "How are you?"
End With

For Each oSection In ActiveDocument.Sections
oSection.Headers.Item(1).LinkToPrevious = True
Next

End Sub


Enjoy! :thumb

Mr Doubtfire
04-20-2005, 06:19 PM
Thanks to ALL of you for the suggestions, ideas, opinions ....

A great place to learn from the knowledgeable and experienced professionals!

MOS MASTER
04-24-2005, 06:39 AM
A great place to learn from the knowledgeable and experienced professionals!
Totally agree on that you're welcome! :beerchug: