Solved

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

Posted on 2014-11-13
4
243 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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
Introduction While answering a recent question (http:/Q_27311462.html), I created an alternative function to the Excel Concatenate() function that you might find useful.  I tested several solutions and share the results in this article as well as t…
This Micro Tutorial will demonstrate in Google Sheets how to use the HYPERLINK function to create live links inside your spreadsheet.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

832 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