Solved

How to do this in VBA and Excel:  <<set target  = Regex.execute(ActiveSheet.EntireSheet)>>

Posted on 2014-11-13
4
239 Views
Last Modified: 2014-11-24
I want to use regular expressions to grab a large list of street addresses from an Excel worksheet.  

It is easy to do this when the lists are in a text file, but I don't see how to do the same with ActiveSheet.


I plan to save the sheet as a csv file then scan that, but I wonder if somebody has a better idea.

The spreadsheets are very big and performance is important, so I don't want to use iterations like For each cell in sheet.cells.


For instance, the following code scans a text file and grabs a large list.  I would like to replace lines 2 to 4 with something that gets the entire activesheet quickly.



Sub t753()
   Open "C:\Users\bob.berke\Desktop\My Master.txt" For Input As #1
    st = Input$(LOF(1), 1)
    Close #1
    
Dim regex As New regexp
Dim ans

regex.Global = True
regex.MultiLine = True
regex.IgnoreCase = True
regex.pattern = "(\t\d{3} \d{3})(.*?)(fax:)"  ' <=== the \t  means "tab", which is roughly equivalent to Excel's "beginning of cell"
Set match = regex.Execute(st)
ans = ""
For Each var In match
    ans = ans & vbCrLf & var
    
    Debug.Print var
Next
ans = Mid(ans, 3)
Dim dobj As New DataObject
dobj.SetText ans
dobj.PutInClipboard
' clipboard will have hundreds of lines that look like <<123 456   City Hall,  Cleveland, OH 44101  Phone:216-505-123 Fax:   >>
End Sub

Open in new window

0
Comment
Question by:rberke
  • 3
4 Comments
 
LVL 85

Expert Comment

by:Rory Archibald
ID: 40439712
Have you speed tested loading the sheet into an array and looping through that? It will be much faster than reading cell by cell.
0
 
LVL 5

Author Comment

by:rberke
ID: 40442108
The spreadsheets contain cells that came from an internet web page

When the pattern "(\t\d{3} \d{3})(.*?)(fax:)" returns 100 matches, each of the 100 elementsmight come from multiple rows.

For instance match (5) might come from 2 rows and match(6) might come from a single row.

.
The sheet has lots of unrelated garbage between the rows that has to be ignored.

so, for Any type of iteration to work, it would first need to concatenate every cell to build a huge concatenated string.    Starting the concatenation with ary = activesheet.usedrange would certainly speed up the process, but I expect saving the spreadsheet to a .csv would be faster still.
0
 
LVL 5

Accepted Solution

by:
rberke earned 0 total points
ID: 40452160
I have been looking for a solution to this kind of problem for several years and now I have it !!!  While I try to be humble, I must say that today I am most pleased with myself.

Sub Macro2()

' the following code use regular expression to parse an entire worksheet with a "Single Execution"
' it works even when the pattern spans multiple cells.
'
'
' 1) replace all tabs and linefeeds with a space and all double quotes with a tick mark. (The tick mark lets us to handle cells containing things <he said "it works">
' 2) save file as tab delimited. Excel add linefeeds after each row and double quotes around most cells.
' 3) read the resulting text file
' 4) remove the double quotes that excel added
' 5) change the Excels to be linefeeds  to be vblf & vbtab. This cause a \t pattern to be treated as "start of a cell"
'    put one extra vblf & vbtab in front of the first row.
' 6) turn the tick marks back into double quotes
' 7) put the resulting matches onto the clipboard.


   [Cells].Replace what:=chr(9), Replacement:=" ", LookAt:=xlPart
   [Cells].Replace what:=chr(34), Replacement:="`", LookAt:=xlPart
   
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs filename:="C:\aaatmp\tempfile.txt", FileFormat:= _
        xlText, CreateBackup:=False
        
        
   Open "C:\aaatmp\tempfile.txt" For Input As #1
    st = Input$(LOF(1), 1)
    st = Replace(st, chr(34), "")
    st = Replace(st, "`", chr(34))
    st = Replace(st, vbLf, vbLf & vbTab)
    st = vbLf & vbTab & st
    Close #1

Dim regex As New regexp
Dim ans

regex.Global = True
regex.MultiLine = True
regex.IgnoreCase = True
regex.pattern = "(\t\d{3} \d{3})(.*?)(fax:)"  ' <=== the \t  means "tab", which is roughly equivalent to Excel's "beginning of cell"
singeExecution: Set match = regex.Execute(st)
ans = ""
For Each var In match
    ans = ans & vbCrLf & var
    
    Debug.Print var
Next
ans = Mid(ans, 3)
Dim dobj As New DataObject
dobj.SetText ans
dobj.PutInClipboard

End Sub

Open in new window

0
 
LVL 5

Author Closing Comment

by:rberke
ID: 40461694
Rory's comment was valid, but I came up with a different solution that was better for my needs.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to read all the sheets in excel 12 31
Compile Error 7 40
Create Excel formula on dynamic data 5 34
FormulaArray VBA Issue 6 17
Whatever be the reason, if you are working on web development side,  you will need day-today validation codes like email validation, date validation , IP address validation, phone validation on any of the edit page or say at the time of registration…
How to quickly and accurately populate Word documents with Excel data, charts and images (including Automated Bookmark generation) David Miller (dlmille) Synopsis In this article you’ll learn how to use ExcelToWord! to copy data,charts, shapes …
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
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…

911 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

21 Experts available now in Live!

Get 1:1 Help Now