使用VBA从两个相同字符之间的string中提取文本

假设我在单元格中有以下string:

E. Stark,T. Lannister,A. Martell,P Baelish,B. Dondarrion和J. Mormont。 维斯特罗斯(Westeros)的裸露程度的增加有助于其零星的季节性气候。 纳特。 PROC。 ACA。 科学。 (2011)3:142-149。

而我只想从中提取标题。 我正在考虑的方法是编写一个脚本,上面写着“从该string中提取文本,但只有超过50个字符”。 这样它只能返回标题,而不是“Stark,T”和“Martell,P”之类的东西。 我到目前为止的代码是:

Sub TitleTest() Dim txt As String Dim Output As String Dim i As Integer Dim rng As Range Dim j As Integer Dim k As Integer j = 5 Set rng = Range("A" & j) 'text is in cell A5 txt = rng.Value 'txt is string i = 1 While j <= 10 'there are five references between A5 and A10 k = InStr(i, txt, ".") - InStr(i, txt, ". ") + 1 'k is supposed to be the length of the string returned, but I can't differenciate one "." from the other. Output = Mid(txt, InStr(i, txt, "."), k) If Len(Output) < 100 Then i = i + 1 ElseIf Len(Output) > 10 Then Output = Mid(txt, InStr(i, txt, "."), InStr(i, txt, ". ")) Range("B5") = Output j = j + 1 End If Wend End Sub 

当然,如果不是两个,那么这个工作就很好。“ 我正在试图从中得到充分的信息。 有没有办法编写InStr函数的方式,它不会find两个相同的字符? 我是否以错误的方式去解决这个问题?

提前致谢,

编辑:可能工作的另一种方法(如果可能的话)是,如果我可以有一个字符是“ any lower case letter 。 和“。”。 这甚至可能吗? 我找不到如何实现这个目标的例子

在这里,你可以按照你的意愿工作。 从你的代码判断,我相信你可以很快适应你的需求:

 Option Explicit Sub ExtractTextSub() Debug.Print ExtractText("E. Stark, T. Lannister, A. Martell, P Baelish, B. Dondarrion, and J. Mormont. Increased levels of nudity across Westeros contributes to its sporadic seasonal climate. Nat. Proc. Aca. Sci. (2011) 3: 142-149.") End Sub Public Function ExtractText(str_text As String) As String Dim arr As Variant Dim l_counter As Long arr = Split(str_text, ".") For l_counter = LBound(arr) To UBound(arr) If Len(arr(l_counter)) > 50 Then ExtractText = arr(l_counter) End If Next l_counter End Function 

编辑:5票在没有时间让我改善我的代码:)这将返回最长的string,没有想到50个字符。 此外,在错误handlaer和点的常量。 另外在摘录的末尾添加一个点。

 Option Explicit Public Const STR_POINT = "." Sub ExtractTextSub() Debug.Print ExtractText("E. Stark, T. Lannister, A. Martell, P Baelish, B. Dondarrion, and J. Mormont. Increased levels of nudity across Westeros contributes to its sporadic seasonal climate. Nat. Proc. Aca. Sci. (2011) 3: 142-149.") End Sub Public Function ExtractText(str_text As String) As String On Error GoTo ExtractText_Error Dim arr As Variant Dim l_counter As Long Dim str_longest As String arr = Split(str_text, STR_POINT) For l_counter = LBound(arr) To UBound(arr) If Len(arr(l_counter)) > Len(ExtractText) Then ExtractText = arr(l_counter) End If Next l_counter ExtractText = ExtractText & STR_POINT On Error GoTo 0 Exit Function ExtractText_Error: MsgBox "Error " & Err.Number & Err.Description End Function