Excel VBA – 删除string内容最多* word *

我试图删除string内容到string中包含的某个单词。 例如

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

我想用VBA来replace它

 "They are red and blue." 

即将所有内容删除到“他们”一词。 我不知道string的内容和它包含的字符的数量。

我不知道如何做到这一点,我真的很感激你的帮助!

干得好:

 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) 

在string中删除所有文本之前的简单示例。

 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 

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

  1. CTRL + H(replace)
  2. *他们(你的星星)

在查找框中。 星号*是一个通配符,可以被称为 – 之前或之后的任何东西(如果添加在结尾处)该单词。

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

这对我很好:

 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