Results 1 to 3 of 3
  1. #1
    2 Star Lounger
    Join Date
    Nov 2001
    Thanked 0 Times in 0 Posts

    Errors when looping through Word doc. Styles (.NET / Office XP)


    I am attempting to loop through the styles of a Word document and add each one to a ComboBox on Form2. However, when I run the code, the ComboBox is filled with the following text:


    I am at a complete loss!

    Here is my code:

    Private Sub MDIForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim i As Integer
    Dim f As New Form2()
    Dim objWord As Word.Application

    objWord = GetObject(, "Word.Application")
    For i = 1 To objWord.ActiveDocument.Styles.Count
    f.ComboBox1.Items.Add (objWord.ActiveDocument.Styles.Item(i))
    End Sub

    Any help on what the problem is would be much appreciated



  2. #2
    Silver Lounger
    Join Date
    Mar 2001
    Springfield, Ohio, USA
    Thanked 2 Times in 2 Posts

    Re: Errors when looping through Word doc. Styles (.NET / Office XP)

    Well, I only have VB6 and Word2K here, but I think you need to define everything and do error checking, plus the biggie is that if you can access the Styles collection with Item(i), you are getting an Style object, so who knows what goes into your combobox. The following code works for me with just a single form and a combobox. I can try it with VB5 & XP, but I really don't think it will make a difference. Try rewriting it like my sample with Option Explicit & the for each loop. How do you like VB.NET? HTH --Sam
    PS (edit) Please don't post the same question on two boards. We read both of them. Thanks!
    <pre>Option Explicit

    Private Sub Form_Load()
    Dim wdApp As Word.Application
    Dim s As Word.Style
    On Error GoTo NoWord
    Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0
    For Each s In wdApp.ActiveDocument.Styles
    If s.InUse Then Combo1.AddItem s.NameLocal
    Next s
    Combo1.ListIndex = 0
    Set wdApp = Nothing
    Exit Sub
    MsgBox "Word must be running!"
    End Sub</pre>

    <font face="Comic Sans MS">Sam Barrett, CACI </font face=comic>
    <small>And the things that you have heard... commit these to faithful men who will be able to teach others also. 2 Timothy 2:2</small>

  3. #3
    Super Moderator jscher2000's Avatar
    Join Date
    Feb 2001
    Silicon Valley, USA
    Thanked 94 Times in 90 Posts

    Re: Errors when looping through Word doc. Styles (.NET / Office XP)

    Let's continue in duplicate thread on VB board.

Posting Permissions

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