Solved

How to use ".net framework regex" in Excel

Posted on 2010-09-03
18
1,153 Views
Last Modified: 2012-05-10
My current and only regex activities are related to Excel and VBA. As I learn more about Regex I miss in VBScript Regular Expression 5.5 a lot of the advanced regex functionality like "mode turning on and off within the regex like (?ism) and (?-ism)" - for i.e. to search "case-insensitive" and replace "case-sensitive".
Q1: Is it possible to use an other regex flavor in Excel for example ".net framework regex" and if so how do I have to accomplish that.
Q2: Am I right, that Office 2007 and 2010 do not provide more regex support?
Q3: Other solutions?

I did not find any clear answers up to now in the Web and the EE knowledge-base except something in that direction on
http://www.devx.com/DevX/Article/28468/0/page/1
but I am not familiar with Visual Studio.

I also found articles about how to use the Excel classes in .net applications but not the contrary.

Thank you for any help
0
Comment
Question by:quexet
  • 6
  • 5
  • 4
  • +1
18 Comments
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
A1:  One possibility would be the use of an API to bring in the functionality.  It looks like the class you want is in the System.dll.  I don't have much experience when I can't find the example already online, so getting you the exact code for this is beyond me at the moment.  You might also be able to set up a Reference in the VBIDE, similar to the way you would do for VB RegEx.

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
0
 
LVL 92

Expert Comment

by:Patrick Matthews
Comment Utility
quexet,

While the RegExp implemented in the .Net framework is admittedly more powerful, I would urge you to look at the UDFs I include in my article here:
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/A_1336-Using-Regular-Expressions-in-Visual-Basic-for-Applications-and-Visual-Basic-6.html

Those UDFs have the same functionality available in the VBScript 5.5 RegExp class. While it lacks look behind, it does include look ahead, and allows either case sensitive/case insensitive searches/replacements.

I find myself using the RegExpFind, RegExpReplace, and RegExpFindSubmatch functions from that article quite frequently.

Patrick
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
Patrick,

I haven't been around in so long, I completely forgot about that article of yours.  Thanks for reminding me.

:)
0
 
LVL 92

Expert Comment

by:Patrick Matthews
Comment Utility
WC,No worries, and hope we see a little more of you around here :)Patrick
0
 
LVL 18

Accepted Solution

by:
WarCrimes earned 250 total points
Comment Utility
Found this cool link, but you would need Visual Studio to make this work.
http://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to-calling-a-net-library-from-excel/

You also may want to look at this:
http://www.cpearson.com/excel/CreatingNETFunctionLib.aspx
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
You could create a COM wrapper for the Regex functionality you seek. Here is a quick example I tested with Excel 2007. COM relies on interfaces, so that's why I created the separate interface describing the functionality provided by this wrapper. The line

    [ClassInterface(ClassInterfaceType.None)]

was added to allow the Intellisense of Office to show the method signatures. It seems you can't declare a parameterized constructor (maybe you can, but I don't have that much experience with COM), so that is why I ended up creating a separate method called SetPattern.
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace RegexWrapper
{
    [ClassInterface(ClassInterfaceType.None)]
    public class Wrapper : IRegex
    {
        private Regex _regex;

        public Wrapper() { }

        public Wrapper(string pattern) { this._regex = new Regex(pattern); }

        public void SetPattern(string pattern)
        {
            this._regex = new Regex(pattern);
        }

        public bool IsMatch(string text)
        {
            if (this._regex == null)
                throw new InvalidOperationException("A pattern must be set prior to calling IsMatch.");

            return this._regex.IsMatch(text);
        }
    }

    public interface IRegex
    {
        bool IsMatch(string text);

        void SetPattern(string pattern);
    }
}

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
P.S.

I forgot to mention that you would mark the project as being "Register for COM Interop" on the Build tab of the project's properties. I believe you also need to set "Make assembly COM-Visible" on the Properteis==>Application==>Assebly Information window.
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
I'm pretty sure that is similar to the link I provided.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Perhaps. I started writing it before I refreshed the page...  apologies.

On the up side, if cpearson.com and wordpress.com ever get taken offline, my example will remain for the benefit of future EE'ers  ;)
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
No worries.  

Cheers,
WC
0
 

Author Comment

by:quexet
Comment Utility
Thanks to you all for responding so fast

WarCrimes: The way you describe in your first comment is what I am looking for, but if possible without me trying to find out the details if they are already common knowledge. If you could find out more in that direction this would be great - your links to good looking Visual Studio articles are way bejond for me.

matthewspatrick: I looked into your article before - great - thanks. For a forthcoming part of the project I might be happy to use your UDFs. But now I would like to use the more sophisticated regex solution in Excel/VBA and I think, that there would be a huge community to be happy with a simple solution.

kaufmed: as mentioned no Visual Studio knowledge here.
0
 

Author Comment

by:quexet
Comment Utility
After having spent some time with the free Visual Basic 2005 Express which comes with Visual Studio 2005 and trying to get the example from the article from Rich Newman or rather the equivalent solution in VB according to Mike Rosenbaum at
http://www.xtremevbtalk.com/printthread.php?t=316618
to work I am still stuck.

Code:
Imports System.Collections.Generic
Imports System.Text
Imports System.Runtime.InteropServices
 
Namespace DotNetLibrary
    <ClassInterface(ClassInterfaceType.AutoDual)> _
    Public Class DotNetClass
        Public Function DotNetMethod(input As String) As String
            Return "Hello " & input
        End Function
    End Class
End Namespace

It compiles ok - no errors - but no reference in Tools/References in Excel VBA. Before I try Regasm - some respect from registry - let me ask the following:

Do I have to get a full blown Version of Visual Studio?
And if yes, which one and am I right to assume, that the 2010 versions should do it alike or better (according to the article from Rich Newmann).

Thank you for further advice.

0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
Comment Utility
Have you tried using Browse under the Add Reference option in Excel? If this is a one-off solution, I think you would be fine by browsing to the appropriate DLL. If you want it to show up in the list of available references, I believe you have to do a regsvr32.exe call to register the DLL--I would need to check on this, though.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
P.S.

You will select the .TLB file, not the .DLL file when you add the reference.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
It appears Regasm is the way to go WRT to the dll showing up in the list of available references.

You should not need to get the full version of VS. Here is a screenshot of what I got after running Regasm against my sample above.
untitled1.JPG
untitled2.JPG
0
 

Author Comment

by:quexet
Comment Utility
kaufmed: thank you - I did not find a tlb file - here my VS project directory content - further assistance possible? Thanks
vb-proj-directory.jpg
0
 

Author Closing Comment

by:quexet
Comment Utility
Thank you all - I was not succesful in getting Net-Regex to work in VBA - I will continue to try it in slower times.
And if somebody wrote an article on this subject I think it would be of great help for many VBA/Net-Regex wannabe's.
@matthewspatrick: your article is great - but is not what I was looking for -  I think I gave you the points in the article area
@WarCrimes: thanks for the good links - did help me to overcome my Visual Studio inhibition threshold
@kaufmed: I appreciate your understanding of my intent and your detailed information in respect to my problem
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Drop Down List with Unique/Distinct Values (Part II - ComboBox or ListBox and Data Validation List Bonus!) David Miller (dlmille) Intro This article focuses on delivering unique, sorted lists to list objects (e.g., ComboBox, ListBox) and Dat…
Approximate matching with VLOOKUP and MATCH seems to me to be a greatly under-used technique, and one which is vital for getting good performance out of large lookups. Until recently I would always have advised using an exact match for simplicity an…
Graphs within dashboards are meant to be dynamic, representing data from a period of time that will change each time the dashboard is updated with new data. Rather than update each graph to point to a different set within a static set of data, t…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now