0

I have an expression input from a user which can be like

{{heading1} + {{heading2} * {heading3}}} 

Each heading is included in braces {} when written in expression.

I want to extract "heading1" "heading2" and "heading3" in a String Array separately using an Excel macros. Please help me with the code.

1
  • I couldn't try anything since I am new to VBA. Only C and Java are my forte. Commented Jan 21, 2015 at 9:23

1 Answer 1

3

You can use regular expressions. Regular expressions are used for Pattern Matching. To use in Excel follow these steps.

Step 1: Add VBA reference to "Microsoft VBScript Regular Expressions 5.5"

  • Select "Developer" tab (I don't have this tab what do I do?)
  • Select "Visual Basic" icon from 'Code' ribbon section
  • In "Microsoft Visual Basic for Applications" window select "Tools" from the top menu.
  • Select "References"
  • Check the box next to "Microsoft VBScript Regular Expressions 5.5" to include in your workbook.
  • Click "OK"

Example

Private Sub regEx()

    Dim UserInput As String
    UserInput = "{{heading1} + {{heading2} * {heading3}}}"

    Dim Pattern As String
    Pattern = "\{([a-zA-Z0-9]*)\}"

    Dim regEx As New RegExp

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = Pattern
    End With

    Dim Matches
    Set Matches = regEx.Execute(UserInput)

    For Each Match In Matches
        Debug.Print "Match found at position " & Match.FirstIndex
        Debug.Print "Match Value is '" & Match.Value & "'"
        Debug.Print ""
    Next

End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

Cool.. Its been really helpful. I have one more question if we can replace heading1, heading2, heading3 and so on in the expression with #1, #2, ...and so on, with consecutive numbers. Can you help me out which function to use for the above?
You can adjust the pattern in between the brackets [a-zA-Z0-9]. At the moment it allows any lower case and upper case letters as well as numbers. If you need other characters you have to modify that pattern. E.g. to allow # change it to [a-zA-Z0-9#]. But be careful some special characters have to be escaped with a backslash as they are used as operators in regular expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.