1

Looking for some help with my macro that loops through subfolders and brings back data from the workbooks that match my filename pattern, because the name changes each month.

It works seamlessly if the pattern is "[0-9][0-9][0-9][0-9][0-9][0-9] Filename"

But fails if "[0-9][0-9][0-9][0-9]_[0-9][0-9] Filename"

Any ideas on how to handle the underscore please?

This fails "[0-9][0-9][0-9][0-9][_][0-9][0-9] Filename"

Thanks heaps GWS

Option Explicit
Option Base 1
Private Const PORTFOLIO_CODE As String = "G030"
Private Sub ExtractData()

' get workbook list

Dim wbList As Collection
Set wbList = New Collection

Application.DisplayAlerts = False

RecursiveFileSearch _
    "O:\Sales and Marketing\Monthly Reports\", _
    "[0-9][0-9][0-9][0-9][_][0-9][0-9] Monthly Report.xlsm", _ 'fails to find any workbooks
  '"[0-9][0-9][0-9][0-9][0-9][0-9]  Monthly Report.xlsm", _ 'would work except my file names contain underscores        
wbList

Dim resultOffset As Integer
wsResult.Name = result
resultOffset = 1

Dim wbName As Variant, wbOpen As Workbook, wsFund As Worksheet
For Each wbName In wbList
    ' loop through workbook list
    ' - open workbook, hidden
    Application.ScreenUpdating = False
    Set wbOpen = Workbooks.Open(Filename:=wbName, ReadOnly:=True)
    wbOpen.Windows(1).Visible = False
    ' - get worksheet for fund
    Set wsFund = wbOpen.Worksheets(PORTFOLIO_CODE)
    Application.ScreenUpdating = True
    ' - find top of data
    Dim valueDate As Date
    valueDate = WorksheetFunction.EoMonth(DateSerial(2000 + CInt(Left(wbOpen.Name, 2)), CInt(Mid(wbOpen.Name, 3, 2)), 1), 0)
    Debug.Print valueDate, wbOpen.Name
    ThisWorkbook.Worksheets(PORTFOLIO_CODE).Activate
    Dim baseData As Excel.Range
    Set baseData = wsFund.Range("AQ:AQ").Find("Currency")
    If Not baseData Is Nothing Then
        ' - loop through data
        Dim rowOffset As Integer
        rowOffset = 0
                wsResult.Range("A1").Offset(resultOffset, 0).Value = valueDate ' baseData.Offset(rowOffset, 0).Value
                wsResult.Range("A1").Offset(resultOffset, 1).Value = baseData.Offset(rowOffset, 0).Value
                wsResult.Range("A1").Offset(resultOffset, 2).Value = baseData.Offset(rowOffset, 5).Value
                resultOffset = resultOffset + 1
    End If
    ' - close workbook
    wbOpen.Close SaveChanges:=False
    DoEvents
Next

Application.DisplayAlerts = True

End Sub

RecursiveFileSearch

Sub RecursiveFileSearch( _
ByVal targetFolder As String, _
ByRef filePattern As String, _
ByRef matchedFiles As Collection _
)

Dim oRegExp As New VBScript_RegExp_55.RegExp
oRegExp.Global = False
oRegExp.IgnoreCase = True
oRegExp.MultiLine = False
oRegExp.Pattern = filePattern

Dim oFSO As Scripting.FileSystemObject
Set oFSO = New Scripting.FileSystemObject

'Get the folder oect associated with the target directory
Dim oFolder As Variant
Set oFolder = oFSO.GetFolder(targetFolder)

'Loop through the files current folder
Dim oFile As Variant
For Each oFile In oFolder.Files
    If oRegExp.test(oFile.Name) Then
        matchedFiles.Add oFile
    End If
Next

'Loop through the each of the sub folders recursively
Dim oSubFolders As Object
Set oSubFolders = oFolder.Subfolders
Dim oSubfolder As Variant
For Each oSubfolder In oSubFolders
    RecursiveFileSearch oSubfolder, filePattern, matchedFiles
Next

'Garbage Collection
Set oFolder = Nothing
Set oFile = Nothing
Set oSubFolders = Nothing
Set oSubfolder = Nothing
Set oFSO = Nothing
Set oRegExp = Nothing
End Sub         
Community
  • 1
  • 1
Glenn Sampson
  • 1,188
  • 3
  • 12
  • 30
  • In my simple test your regex works just fine BUT, I noticed that you have one space before the word Monthly in your pattern that has the underscore and two spaces in the one that works without the underscore. When I changed that it worked for me on this example: `1234_56 Monthly Report.xlsm` – Automate This Oct 31 '14 at 00:24
  • FYI - You can simplify your pattern a little too: `[0-9]{4}[_][0-9]{2} Monthly Report.xlsm` The `{}` is a multiplier of the preceding pattern. This is helpful when you have a varing number of digits because you can specify a range like this: `[0-9]{3,4}` which mean match 3 or 4 digits from 0 to 9. You might also [find this link useful](http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops/22542835#22542835) – Automate This Oct 31 '14 at 00:30
  • thanks for the thoughts and testing. the true file name is "[0-9][0-9][0-9][0-9][_][0-9][0-9] SAMPSON International Shares Passive (Hedged) Trust Mandate Monthly Report.xlsm" do you think the length maybe throwing the error? – Glenn Sampson Oct 31 '14 at 00:47
  • Are you escaping the parentheses around `(Hedged)`? That should look like `\(Hedged\)` in your regex. – briantist Oct 31 '14 at 00:54
  • 1
    Try this: `^[0-9]{3,4}[_][0-9]{2} SAMPSON International Shares Passive \(Hedged\) Trust Mandate Monthly Report\.xlsm` It's escaping the () and . to override the defined regex behavior. – Automate This Oct 31 '14 at 00:55
  • 2
    Perhaps: **\d{4}_\d{2}.*Monthly Report\.xlsm** – Ron Rosenfeld Oct 31 '14 at 00:59
  • @RonRosenfeld: That is a valid answer :) I would recommend posting it so that it can help future visitors. Comments are temporary ;) – Siddharth Rout Oct 31 '14 at 01:08
  • @GlennSampson I added it as an answer, and would be pleased if you marked it as such. – Ron Rosenfeld Oct 31 '14 at 02:02
  • @SiddharthRout At the time I wrote that comment, I wasn't certain of all of his requirements, and didn't want to clutter things up. Thanks. – Ron Rosenfeld Oct 31 '14 at 02:04
  • my apologies @RonRosenfeld. I thought the last comment by glenn above was for you. After reading his answer. I guess it was for portland :) – Siddharth Rout Oct 31 '14 at 07:38
  • @SiddharthRout No apologies necessary. Sometimes things are difficult to interpret in this venue – Ron Rosenfeld Oct 31 '14 at 10:58

2 Answers2

1

My code was escaping the () and . to override the defined regex behavior. Portland Runner suggestion solved the question. ^[0-9]{3,4}[_][0-9]{2} SAMPSON International Shares Passive (Hedged) Trust Mandate Monthly Report.xlsm

Glenn Sampson
  • 1,188
  • 3
  • 12
  • 30
1

Perhaps:

\d{4}_\d{2}.*Monthly Report\.xlsm
Ron Rosenfeld
  • 53,870
  • 7
  • 28
  • 60