Solved

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

Posted on 2014-11-13
4
252 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

Freeze panes is an option within all variants of Excel to enable parts of a sheet to remain stationary when the cursor is in another part of the sheet. This is a very useful feature which is overlooked or under used.
You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
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…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

737 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