Home > Blockchain >  Proper way to return elements of (ThisWorkbook.name) before the element of Format (Date)
Proper way to return elements of (ThisWorkbook.name) before the element of Format (Date)

Time:06-10

I have file with name All PM 7.6 10-Jun v2 , All PM 7.6 is a dynamic name and (10-Jun) is static name formulated using Format(Date, "DD-MMM")
I want to get these elements (All PM 7.6) ,I tried the following:

Dim arrname, strExisting As String   
arrname = Split(ThisWorkbook.name, ".")
strExisting = arrname(0) & "." & arrname(1)

I think using arrname(0) & "." & arrname(1) is not the proper way to get it ,as if this parts of name changed then I need to modify the code again.

In advance, thanks for all your help.

CodePudding user response:

Since you did not clarify (at least, for me) what is to be returned, please use the next function to extract the date string:

Function ExtractDateStr(strName As String) As String
    Dim arr: arr = Split(strName, " ")
    Dim strD As String: strD = arr(UBound(arr) - 1)
   
    ExtractDateStr = strD
End Function

It can be used in the next way, to return the prefix before the date string or each element up to it:

Sub testExtractWbNameElements()
   Dim x As String, strPrefix As String
   x = "All PM 7.6 10-Jun v2.xlsx"
   Debug.Print ExtractDateStr(x)
   strPrefix = left(x, InStr(x, " " & ExtractDateStr(x)) - 1)
   Debug.Print strPrefix 'the string before the date part
   
   Dim arrElem
   arrElem = Split(strPrefix, " ") 'each elements up to the date part, in an array:
   Debug.Print UBound(arrElem), Join(arrElem, "|") 'just proving the return...
End Sub

The above solution assumes that the elements before the date part may be different in terms of number. If only three, as in your example, the solution can be simpler..

Edited:

If the first elements to be returned will always be three, use the next simpler way:

Sub testSplitSpecElemNo()
   Dim x As String, arr
   x = "All PM 7.6 10-Jun v2.xlsx"
   arr = Split(x, , 4, 0) '4 means how many elements to return. First three and the last one (the rest all toghether) like the foourth
   arr(UBound(arr)) = "$#@%&" 'characters not very probable to exist like such a group in the other array elements...
   arr = filter(arr, arr(UBound(arr)), False) 'eliminate the last global one
   Debug.Print Join(arr, "|")
End Sub
  • Related