【问题标题】:Excel VBA - delete string content up to *word*Excel VBA - 删除字符串内容最多 *word*
【发布时间】:2017-09-25 22:00:02
【问题描述】:

我正在尝试删除字符串内容,直到字符串中包含的某个单词。例如

"Emily has wild flowers. They are red and blue."

我想使用 VBA 来替换它

"They are red and blue."

即删除“他们”之前的所有内容。我不知道字符串内容和其中包含的字符数。

我不知道该怎么做,非常感谢您的帮助!

【问题讨论】:

    标签: string vba excel


    【解决方案1】:

    给你:

    Dim s As String
    s = "Emily has wild flowers. They are red and blue."
    
    Dim indexOfThey As Integer
    
    indexOfThey = InStr(1, s, "They")
    
    
    Dim finalString As String
    finalString = Right(s, Len(s) - indexOfThey + 1)
    

    【讨论】:

    • 请注意,您不需要计算字符串的长度。 finalString = Mid(s, indexOfThey),和Mid一样,长度可选
    • 这也将捕获部分单词。如果您在“I'll take the algorithm to go.”中搜索“go”,您将得到“gorithm to go”。
    【解决方案2】:

    删除字符串中值之前的所有文本的简单示例。

    Sub Foo()
        Dim strOrig As String
        Dim strReplace As String
        strOrig = "The Quick brown fox jumped over the lazy dogs"
        strReplace = "jumped"
    
        MsgBox (DropTextBefore(strOrig, strReplace))
    
    End Sub
    
    Public Function DropTextBefore(strOrigin As String, strFind As String)
        Dim strOut As String
        Dim intFindPosition As Integer
        'case insensitive search
        'could made it so that case sensitivity is a parameter but this gets the idea across.
        If strOrigin <> "" And strFind <> "" Then
            intFindPosition = InStr(UCase(strOrigin), UCase(strFind))
            strOut = Right(strOrigin, Len(strOrigin) - (intFindPosition + Len(strFind) - 1))
        Else
          strOut = "Error Empty Parameter in function call was encountered."
        End If
        DropTextBefore = strOut
    End Function
    

    【讨论】:

      【解决方案3】:

      如果这个词是固定的,比如上面例子中的“他们”,你可以简单地做

      1. CTRL + H(替换)
      2. *他们(你的话加星)

      在“查找”框中。星号 * 是一个通配符,可以在单词之前或之后(如果添加在末尾)的任何内容中称为 -。

      小心:当你在同一个单元格中有重复的单词时要小心。

      【讨论】:

      • 谢谢,但我需要的应用程序更复杂,需要 VBA 驱动。
      • 为什么它被否决了......它在哪里写到这是一个复杂且需要 VBA 驱动的策略......
      • 我猜“我想使用 VBA”以及 vbaexcel-vba 标签表示 VBA,再加上你的方法很危险,而且没有解决“他们”一词之前的文本可能会更改的事实。它没有抓住问题的重点,也没有安全地回答它。
      • 天哪...我应该正确阅读这个问题...一节课
      • 我对此表示赞同,因为我打算使用 VBA 来解决它,而这个答案表明我过于复杂了。
      【解决方案4】:

      这对我很有用:

      Sub remove_until()
      
      Dim i, lrowA, remChar As Long
      Dim mString As String
      
      lrowA = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
      
      For i = 1 To lrowA
      
      mString = Cells(i, 1).Value
      
      
          If InStr(mString, "They") > 0 Then
      
          remChar = Len(mString) - InStr(mString, "They") + 1
      
          Cells(i, 2).Value = Left(mString, Len(mString) - remChar)
      
          End If
      
      
      Next
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多