vba 如何获取字符串的特定部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2543225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a particular part of a String
提问by Harish
I am writing a macro in Excel where I need to get a substring from a String. It's like this.
我正在 Excel 中编写一个宏,我需要从字符串中获取子字符串。就像这样。
~/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 InStrbut it's not useful. Can anyone help?
在上述情况下,我需要从第一个中取出 String 测试器并从第二个中取出。我尝试使用InStr但它没有用。任何人都可以帮忙吗?
回答by Rune Grimstad
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.
您可以使用 InStr 和 Mid 函数执行此操作。使用 InStr 函数查找 / 的出现次数,然后使用 Mid 获取您感兴趣的字符串部分。
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.
此功能将产生所需的结果。
回答by Jojo Sardez
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
回答by kriss
As far as I know there is no regex in Excel, you have to do what you want "by hand".
据我所知,Excel 中没有正则表达式,你必须“手工”做你想做的事。
You can do it using Instr as others showed.
你可以像其他人展示的那样使用 Instr 来做到这一点。
Below another solution using Split (this function is available for Excel 2000 and above)
下面使用 Split 的另一种解决方案(此功能适用于 Excel 2000 及更高版本)
Function ExtractFirstPartOfPath(path as String) as String
Dim parts
parts = Split(path, "/")
ExtractFirstPartOfPath = parts(1)
End Function

