简体   繁体   中英

Excel - Knowing 5 first digits, find a path to path a file using VBA and Regex

I'm working in an environment with always follow this hierarchy:

F:\Client Documents\"JobCategory"\"JobNumber-ClientName"\Estimate

Being:

  • JobNumber always the 2 digits year follow by 3 sequential digits eg: 15255 (255th job of 2015 )
  • JobCategory is used to separate jobs by hundreds, eg, the above job # will be found in folder 15200
  • ClientName is the problem , where obviously can be any name...

So at the moment, I have to type correctly the whole job number and name and trough excel I extract the job category and so on... but in order to automatize some other macros. Is there any way where the script finds (or search/match) the first 5 digits and if it match, use that name as a path?

Eg. if I know job # 15255, F:\\Client Documents\\15200\\15255-JohnSmith or \\15255-JohnSnow will be a match?

If relevant... the VBA script I have so far to save my workbook is:

Dim JobCat As String, JobDetails As String
 JobCat = Sheet12.Range("P4").Text
  JobNumber = Sheet12.Range("P5").Text

ActiveWorkbook.SaveAs Filename:= _
    "F:\Client Documents\" & JobCat & "\" & JobDetails & "\Estimate.xlsm" _
    , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub

Where in P5 I type the hole JobNumber-ClientName and P4 extract its Number category.

Any help, even to clarify if it's possible will be helpful

You can use the Dir function to get the first Folder that matches your search string (if you run Dir without parameters after the first execution, you will get the next Folder that matches the search string)

This should work for you:

Public Sub saveMe()
Dim JobCat As String, JobDetails As String
Dim Path As String

JobCat = Sheet12.Range("P4").Text
JobNumber = Sheet12.Range("P5").Text

Path = Dir("F:\Client Documents\" & JobCat & "\" & JobDetails & "*", vbDirectory)

If Path <> "" Then
    ActiveWorkbook.SaveAs Filename:= _
        Path & "\Estimate.xlsm" _
        , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End If
End Sub

Thanks to @Dorian , had to modify a little bit it's path so my final script is:

Public Sub saveMe()
Dim JobCat As String, JobNumber As String
Dim Path As String

JobCat = Sheet1.Range("A5").Text
JobNumber = Sheet1.Range("A4").Text

Path = Dir("C:\test\" & JobCat & "\" & JobNumber & "*", vbDirectory)

If Path <> "" Then
 ActiveWorkbook.SaveAs Filename:= _
    "C:\test\" & JobCat & "\" & Path & "\Estimate.xlsm" _
    , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM