Results 1 to 20 of 20

Thread: Solved: Word.application help

  1. #1

    Solved: Word.application help

    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.

  2. #2
    VBAX Master Killian's Avatar
    Joined
    Nov 2004
    Location
    London
    Posts
    1,132
    Location
    Hi and welcome to VBAX

    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:[VBA]ActiveDocument.Paragraphs(3).Range.Font.Size = 14[/VBA]
    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:[VBA]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[/VBA]
    K :-)

  3. #3
    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!

  4. #4
    VBAX Tutor TheAntiGates's Avatar
    Joined
    Feb 2005
    Location
    Tejas
    Posts
    263
    Location
    If I may jump in...is using Characters object acceptable?[VBA]For i = Selection.Start To Selection.End
    ActiveDocument.Characters(i).Font.Size = iNewSize
    Next i[/VBA]I 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?
    I just found a cool semi-advanced VBA page - dictionary, queue, etc. http://analystcave.com/excel-vba-dic...ta-structures/

  5. #5
    VBAX Master Killian's Avatar
    Joined
    Nov 2004
    Location
    London
    Posts
    1,132
    Location
    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 [VBA]Selection.Range.Font.Size = iNewSize[/VBA]
    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.
    K :-)

  6. #6
    VBAX Tutor TheAntiGates's Avatar
    Joined
    Feb 2005
    Location
    Tejas
    Posts
    263
    Location
    Thanks - point well taken. But I will confess my hidden agenda in using Characters(), FYI. The actual code is[VBA]For i = Selection.Start To Selection.End
    If ActiveDocument.Characters(i).Font.Size = iOldSize Then
    ActiveDocument.Characters(i).Font.Size = iNewSize
    end if
    Next i[/VBA]I 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. 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" ...
    I just found a cool semi-advanced VBA page - dictionary, queue, etc. http://analystcave.com/excel-vba-dic...ta-structures/

  7. #7
    Killian,

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

  8. #8
    VBAX Tutor TheAntiGates's Avatar
    Joined
    Feb 2005
    Location
    Tejas
    Posts
    263
    Location
    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.
    I just found a cool semi-advanced VBA page - dictionary, queue, etc. http://analystcave.com/excel-vba-dic...ta-structures/

  9. #9
    VBAX Master Killian's Avatar
    Joined
    Nov 2004
    Location
    London
    Posts
    1,132
    Location
    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.[VBA]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
    Next[/VBA]You'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 )

    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)[VBA]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[/VBA]
    K :-)

  10. #10
    VBAX Tutor TheAntiGates's Avatar
    Joined
    Feb 2005
    Location
    Tejas
    Posts
    263
    Location
    Quote Originally Posted by Killian
    With Selection.Range.Find
    Freaking beautiful solution. My mind was up on the first half of your post but you warp-sped me way ahead!

    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!
    I just found a cool semi-advanced VBA page - dictionary, queue, etc. http://analystcave.com/excel-vba-dic...ta-structures/

  11. #11
    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.

    [vba]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[/vba]

    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.

  12. #12
    Site Admin
    Urban Myth
    VBAX Guru
    Joined
    May 2004
    Location
    Oregon, United States
    Posts
    4,940
    Location
    Mr. Doubtfire: [uvba]some info for you[/uvba] I edited your post to include them, hope that is ok with you.

  13. #13
    VBAX Master Killian's Avatar
    Joined
    Nov 2004
    Location
    London
    Posts
    1,132
    Location
    Just changing the focus for a moment, you might want to read this 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
    K :-)

  14. #14
    [VBA]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[/VBA]


    I ran it with object missing.
    Please comment .Thanks.
    Last edited by Killian; 04-19-2005 at 01:19 AM. Reason: Adding VBA tags

  15. #15
    VBAX Master geekgirlau's Avatar
    Joined
    Aug 2004
    Location
    Melbourne, Australia
    Posts
    1,464
    Location
    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".
    [VBA]
    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
    [/VBA]

    Oops - you'll also need the following:

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

    <rest of code>

  16. #16
    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!

  17. #17
    VBAX Tutor TheAntiGates's Avatar
    Joined
    Feb 2005
    Location
    Tejas
    Posts
    263
    Location
    Quote Originally Posted by Mr Doubtfire
    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.
    I just found a cool semi-advanced VBA page - dictionary, queue, etc. http://analystcave.com/excel-vba-dic...ta-structures/

  18. #18
    Administrator
    VP-Knowledge Base
    VBAX Guru MOS MASTER's Avatar
    Joined
    Apr 2005
    Location
    Breda, The Netherlands
    Posts
    3,281
    Location
    Quote Originally Posted by Mr Doubtfire
    I should still have questions.
    Hi,

    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!

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

    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:[VBA]
    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
    [/VBA]

    Enjoy!
    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.
    (I don't answer questions asked through E-mail or PM's)

  19. #19
    Thanks to ALL of you for the suggestions, ideas, opinions ....

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

  20. #20
    Administrator
    VP-Knowledge Base
    VBAX Guru MOS MASTER's Avatar
    Joined
    Apr 2005
    Location
    Breda, The Netherlands
    Posts
    3,281
    Location
    Quote Originally Posted by Mr Doubtfire
    A great place to learn from the knowledgeable and experienced professionals!
    Totally agree on that you're welcome!
    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.
    (I don't answer questions asked through E-mail or PM's)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •