Excel VBA - 删除*word*后的字符串内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39593007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:19:08  来源:igfitidea点击:

Excel VBA - delete string content after *word*

vbaexcel-vbaexcel

提问by Black

I'm trying to delete string content before a certain word contained within the string. For example

我试图在字符串中包含的某个单词之前删除字符串内容。例如

[email protected]

I'd like to use VBA in order to replace that with

我想使用 VBA 来替换它

master_of_desaster

Everything after the "word" (@) should be removed, including the "word" itself.

应删除“单词”(@) 之后的所有内容,包括“单词”本身。

I found a similar topic here, but he asks the opposite.

我在这里找到了一个类似的话题,但他提出了相反的问题。

回答by Black

email = "[email protected]"

ret = Left(email, InStr(1, email, "@") - 1)

Result: master_of_desaster

结果:master_of_desaster

Thanks to Shai Rado

感谢Shai Rado

回答by Slai

A bit hacky but fast ( most Windows API accept zero terminated strings )

有点hacky但很快(大多数Windows API接受零终止字符串)

ret = Replace("[email protected]", "@", vbNullChar, , 1) ' Chr(0)

I usually use the Split method but with Limit:

我通常使用 Split 方法,但有限制:

ret = Split("[email protected]", "@", 2)(0)

回答by luke_t

Just for fun - a regex approach.

只是为了好玩 - 正则表达式方法。

Public Sub reg()

    Dim re_pattern As String
    Dim re As RegExp
    Dim email As String
    Dim match As Object

    Set re = New RegExp

    email = "[email protected]"
    re_pattern = "(.*)@.*"

    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = re_pattern
    End With

    Set match = re.Execute(email)

    Debug.Print match.Item(0).SubMatches(0)

End Sub

回答by Nathan_Sav

=split("[email protected]","@")(0)

=split("[email protected]","@")(0)

回答by Rosetta

ret = evaluate("left(" & string & ", search(""@"", " & string & ") - 1)")