Serving the Quantitative Finance Community

 
User avatar
dowjones123
Topic Author
Posts: 0
Joined: March 19th, 2008, 10:31 am

Parsing stringes like 5Y3M2D in VBA

January 11th, 2013, 4:58 pm

HiI am trying to write a function that would be like =userDateAdd (Date1 as Date, PeriodString as String) that would simply return Date2 by adding the interval denoted by PeriodString to Date1I am sure this is somewhere online/written by someone and I need not re-invent the wheel. How should I write the code for parsing the PeriodString (like "5Y3M2d")Thanks for the pointers in advance
 
User avatar
tags
Posts: 3603
Joined: February 21st, 2010, 12:58 pm

Parsing stringes like 5Y3M2D in VBA

January 11th, 2013, 8:04 pm

Are your period lengths actually in the format "5Y3M2d"?
Last edited by tags on January 10th, 2013, 11:00 pm, edited 1 time in total.
 
User avatar
dowjones123
Topic Author
Posts: 0
Joined: March 19th, 2008, 10:31 am

Parsing stringes like 5Y3M2D in VBA

January 11th, 2013, 10:02 pm

No, but I want to write a library that is flexible to handle such date formats, if I can't find anything available already. Many thanks
 
User avatar
tula

Parsing stringes like 5Y3M2D in VBA

January 11th, 2013, 10:33 pm

you can use regular expressions in VBA as well
 
User avatar
tags
Posts: 3603
Joined: February 21st, 2010, 12:58 pm

Parsing stringes like 5Y3M2D in VBA

January 13th, 2013, 2:25 pm

Following Tula's suggestion:Function dateRegex(dat As Date, timlen As String) As Date' Function that takes a date in a date format +' a time length in string format and returns a' date in a VBA date format' Create regexDim reg As RegExp' Create the regex object for the yearSet reg = New RegExpWith reg .IgnoreCase = True ' Case insensitive, just in case ... .Global = True ' Several occurrence to be found .Pattern = "\d+" ' Find out the year, month and day into the stringEnd WithDim mat As ObjectSet mat = reg.Execute(timlen)' Create variables to store date calculation resultsDim res1 As Date, res2 As Date, res3 As Dateres1 = DateAdd("yyyy", mat(0), dat)res2 = DateAdd("m", mat(1), res1)res3 = DateAdd("d", mat(2), res2)' Return the desired value to the sheetdateRegex = res3 End Function That works well here. Please, tell me if it is okay for you.
Last edited by tags on January 12th, 2013, 11:00 pm, edited 1 time in total.