Results 1 to 3 of 3
  1. #1
    4 Star Lounger
    Join Date
    Apr 2001
    Posts
    482
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Find string in style name

    I need to check if a string is in the name of the style of the selected text. For example if Selection.Range.Style contains "stylename", then I need to perform some actions. The style name may not be exactly what I am looking for. It could equal "stylename" or it may also be "stylename_1" or "stylename_2" etc.

    I have tried a few things, but with no success. It has been a while since I have worked in VBA. Can you help?

    Thanks!!
    Troy

  2. #2
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Troy,

    Here's a function that will do the test:
    Code:
    Option Explicit
    
    Public Function bTestForStyleContents(zSearchValue As String) As Boolean
    
       Dim zStyleName As String
       
       zStyleName = Selection.Range.Style
       
       If InStr(UCase(zStyleName), UCase(zSearchValue)) > 0 Then
       
         MsgBox "The selected text style: " & zStyleName & vbCrLf & _
                "Contains the search value: " & zSearchValue, _
                vbOKOnly + vbInformation, _
                "Style Search Results:"
         bTestForStyleContents = True
       Else
          MsgBox "The selected text style: " & zStyleName & vbCrLf & _
                "Does NOT contain the search value: " & zSearchValue, _
                vbOKOnly + vbInformation, _
                "Style Search Results:"
         bTestForStyleContents = False
       End If
       
    End Function  'bTestForStyleContents
    The msgbox code is there for testing purposes only and can be commented out or removed when you are happy with the results.

    To use the function in your code just include it in an if statement passing the value you want to search for, e.g. to search for Box in the style name:
    Code:
      If bTestForStyleContents("Box") then
        '*** Your code here for condition where value is in the style name    ***
      Else
        '*** Your code here for condition where value is NOT in the style name ***
      Endif
    Note: Code is Case insensitive! If you want case sensitive code remove the UCase staments from the IF test in the function.

    HTH
    Last edited by RetiredGeek; 2015-04-06 at 12:51.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  3. #3
    4 Star Lounger
    Join Date
    Apr 2001
    Posts
    482
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Perfect! Just what I needed. Thanks!!

Posting Permissions

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