Results 1 to 9 of 9

Thread: Solved: Help searching document for Character Styles

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    VBAX Master
    Joined
    Feb 2011
    Posts
    1,480
    Location
    This is a good example of when to modularize your code to make it simpler to adjust and troubleshoot. Whenever you're repeating code chunks, that's an indication you can use a subroutine to do the same thing, but using parameters. For instance..
    [vba]
    Sub frosty_geek()
    '
    ' frosty_geek Macro
    '
    '
    Dim oExcel As Object
    Dim oBook As Object

    ' use existing instance of Excel if possible
    On Error Resume Next
    Set oExcel = GetObject(, "Excel.Application")

    If Err.Number <> 0 Then
    Set oExcel = CreateObject("Excel.Application")
    End If

    ' should use proper error handling here
    On Error GoTo 0
    'create the workbook
    Set oBook = oExcel.Workbooks.Add

    'with the first sheet of the work book...
    With oBook.Sheets(1)
    'do the first style
    FindStyleAndPutInExcel "Activity Footage", .Range("A2")

    'and the second...
    FindStyleAndPutInExcel "New Word", .Range("B2")

    'and the third... you get the idea
    FindStyleAndPutInExcel "Title Graphics", .Range("C2")
    End With

    ExitHere:
    On Error Resume Next
    oExcel.Visible = True
    oExcel.Activate

    Set oBook = Nothing
    Set oExcel = Nothing
    End Sub
    Public Sub FindStyleAndPutInExcel(sStyleName As String, oExcelRng As Object)
    Dim rngSearch As Range
    Dim l As Long

    Set rngSearch = ActiveDocument.Content
    With rngSearch.Find
    .Style = sStyleName
    .Wrap = wdFindStop
    .Format = True
    'now execute until you don't find it
    Do Until .Execute = False
    oExcelRng.Offset(l, 0).Formula = rngSearch.Text
    l = l + 1
    Loop
    End With
    End Sub
    [/vba]
    Last edited by Frosty; 06-01-2012 at 10:13 AM.

Posting Permissions

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