开发者

How to get a particular part of a String

开发者 https://www.devze.com 2022-12-24 21:47 出处:网络
I am writing a macro in Excel where I need to get a substring from a String. It\'s like this. 开发者_开发百科~/tester/test/hai/bye

I am writing a macro in Excel where I need to get a substring from a String. It's like this.

开发者_开发百科~/tester/test/hai/bye
~/stack/overflow/hai/bye

In the above cases I need to take the String tester from the first one and stack from the second one. I tried using InStr but it's not useful. Can anyone help?


You can do this using the InStr and Mid functions. Use the InStr function to find the occurrences of the / and then use Mid to get the part of the string that you are interested in.

Try this:

Function ExtractFirstPartOfPath(path as String) as String

  Dim first, second as Integer

  first = InStr(path, "/")
  second = InStr(first + 1, path, "/")

  ExtractFirstPartOfPath = Mid(path, first + 1, second - first - 1)

End Function

This function will produce the desired results.


Try this:

Sub Macro1()
    Dim text As String, result As String
    text = "~/tester/test/hai/bye"
    result = Mid(text, 3, InStr(3, text, "/") - 3)
    'MsgBox is for demo only
    MsgBox result
End Sub


As far as I know there is no regex in Excel, you have to do what you want "by hand".

You can do it using Instr as others showed.

Below another solution using Split (this function is available for Excel 2000 and above)

Function ExtractFirstPartOfPath(path as String) as String

    Dim parts
    parts = Split(path, "/")
    ExtractFirstPartOfPath = parts(1)

End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号