Solved

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

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
Do you use a spreadsheet like Microsoft's Excel?  Have you ever wanted to link out to a non excel file on your computer or network drive?  This is the way I found to do it!
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

789 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