0

how can we extract a substring from a string if we give the positions of first and last letter in string?

Dim my_string As String
Dim my_substring As String
my_string="Excel/Sheet1.xls"

instrrev(my_string,"/") gives 6 (start position)

len(my_string) gives 16 (end position)

So to get "Sheet1.xls" as my substring what should we do?

Or we can get it selecting characters till "/" is met first/

Community
  • 1
  • 1
Abdul Shiyas
  • 401
  • 3
  • 9
  • 30

3 Answers3

4

How about this one?

my_substring = Split("Excel/Sheet1.xls","/")(1)
Tom
  • 747
  • 5
  • 16
  • 1
    This won't do what you expect it to do if there is more than one `/` in the string. Why not change it a bit to store the `Split` in a `Variant`, then get the *last* element with `UBound`? – LondonRob Jun 30 '15 at 10:11
  • May I suggest this slight improvement: `Split(strFileName, "/")(UBound(Split(strFileName, "/")))` – Ralph Jun 30 '15 at 10:17
  • Ralph, in that case I would consider putting the array in a variant variable so that the split function does not have to execute twice. But it is true that my suggestion would not work with more than one /. It is even advisable to check if there are any.... – Tom Jun 30 '15 at 10:29
2
Mid(my_string,instrrev(my_string,"/")+1, len(my_string))

would give you Sheet1.xls.

Abdul Shiyas
  • 401
  • 3
  • 9
  • 30
waka
  • 3,362
  • 9
  • 35
  • 54
1

How about this solution:

Dim strFileName As String
strFileName = ActiveWorkbook.Path & "/" & ActiveWorkbook.Name
Debug.Print "Start Position: " & Len(strFileName) - InStr(1, StrReverse(strFileName), "/")
Debug.Print "Extacted file name: " & Mid(strFileName, Len(strFileName) - InStr(1, StrReverse(strFileName), "/") + 2)
Ralph
  • 9,284
  • 4
  • 32
  • 42