gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:15:55 28 4
gpt4 key购买 nike

假设我在一个单元格中有以下字符串:

E. Stark、T. Lannister、A. Martell、P Baelish、B. Dondarrion 和 J. Mormont。维斯特洛的裸露程度增加导致其零星的季节性气候。纳特。过程。阿卡。科学。 (2011) 3: 142-149。

我只想从中提取标题。我正在考虑的方法是编写一个脚本,上面写着“从这个字符串中提取文本,但前提是它的长度超过 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以这样的方式运行,它不会两次找到相同的字符?我会以错误的方式解决这个问题吗?

提前致谢,

编辑:另一种可能有效的方法(如果可能的话)是如果我可以让一个字符成为“ 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 票立刻让我改进了我的代码 :) 这将返回最长的字符串,而不考虑 50 个字符。此外,在错误处理程序和点的常量上。加上在提取的末尾添加一个点。
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

关于vba - 使用VBA从两个相同字符之间的字符串中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38222798/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com