简体   繁体   English

Excel VBA-如何从给定的字符串中提取文本

[英]excel vba - how to extract a text from a given string

I have the following text in a cell. 我在单元格中有以下文本。

I am using stackoverflow. 我正在使用stackoverflow。
Stackoverflow is a question and answer forum. Stackoverflow是一个问答论坛。
Let's say I have one more line. 假设我还有一行。

I have split this into an array. 我将其拆分为一个数组。

Arr[0] = I am using stackoverflow.   
Arr[1] = Stackoverflow is a question and answer forum.   
Arr[2] = Let’s say I have one more line.

How can I specifically retrieve the string from Arr[1] from answer till forum. 如何从answer till forum.Arr[1]专门检索字符串answer till forum.

Output should be - answer forum 输出应该是- answer forum

Use substring. 使用子字符串。

Dim substring As String = RIGHT(arr[1], 13)

where 13 can be replaced with the length of the substring. 其中13可以替换为子字符串的长度。 Make sure the length isn't going to cause an index out of bounds exception. 确保长度不会导致索引超出范围异常。

This might not be the most robust answer depending on what your use case is. 根据您的用例,这可能不是最可靠的答案。 But the right() function will work. 但是right()函数将起作用。

answerString = Right(Arr(1), 13)
'answer forum.

I will assume that you don't know exactly where in your Arr(1) that the word "answer" occurs, and that the word "forum" does not occur directly after it, ie that the variable Arr(1) might contain the string "Stack Overflow is a question and answer site and is not a forum like so many other sites" . 我将假设您不完全知道Arr(1)中的单词“答案”出现在哪里,并且单词“ forum”不是紧随其后出现的,即变量Arr(1) 可能包含字符串"Stack Overflow is a question and answer site and is not a forum like so many other sites" (Which is actually a better description of Stack Overflow!) (实际上是对堆栈溢出的更好描述!)

Dim temp As String
Dim result As String
arr(1) = "Stack Overflow is a question and answer site and is not a forum like so many other sites"

'Get everything after the first occurrence of "answer"
temp = Mid(arr(1), InStr(arr(1), "answer"))

'Get everything before the first occurrence of "forum"
result = Left(temp, InStr(temp, "forum") + 4)  ' + 4 because the InStr will point to the "f" of "forum"

'result will contain "answer site and is not a forum"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM