从VBA中的字符串中删除子字符串(remove a sub

编程入门 行业动态 更新时间:2024-10-25 16:24:12
从VBA中的字符串中删除子字符串(remove a sub-string from a string in VBA)

我在VBA中有两个字符串可以说,

Dim str1 as String Dim str2 as String str = "I.3) Haupttätigkeit(en)"

str2= "I.3)"

我想从str1中删除str2。 在VBA有可能吗?

这就是我在做的事情:

Dim strResult As String ' Position of str1 intPos = InStr(1, str1, str2) If intPos > 0 Then ' str2 found, strResult = Left(str1, intPos - 1) Else ' str2 not found, so take whole string strResult = str1 End If

I have two strings in VBA lets say,

Dim str1 as String Dim str2 as String str = "I.3) Haupttätigkeit(en)"

and

str2= "I.3)"

I want to remove str2 from str1. Is it possible in VBA ?

This is what I am doing:

Dim strResult As String ' Position of str1 intPos = InStr(1, str1, str2) If intPos > 0 Then ' str2 found, strResult = Left(str1, intPos - 1) Else ' str2 not found, so take whole string strResult = str1 End If

最满意答案

你需要的是使用Replace function很简单:

str1 = Replace(str1, str2, "") 'result: Haupttätigkeit(en)

但是,它会在更换后保留前导空间,因此您可以尝试这种方式(删除前导或结束空格):

str1 = Trim(Replace(str1, str2, "")) 'result:Haupttätigkeit(en)

或者,您可以使用此处所述的 Mid Statement 。

What you need is quite simple to do with Replace function:

str1 = Replace(str1, str2, "") 'result: Haupttätigkeit(en)

However, it will keep leading space after replacement, therefore you could try in this way (removing leading or ending spaces):

str1 = Trim(Replace(str1, str2, "")) 'result:Haupttätigkeit(en)

Alternatively you could use Mid Statement as described here.

更多推荐

本文发布于:2023-08-06 04:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444770.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   VBA   remove

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!