Removing particular string from a cell

时间:2015-07-08 16:00:17

标签: excel excel-vba vba

I have text in a range of cells like

Manufacturer#||#Coaster#|#|Width (side to side)#||#20" W####Height (bottom to top)#||#35" H#|#|Depth (front to back)#||#20.5" D####Seat Depth#||#14.25"**#|#|Material & Finish####**Composition#||#Wood Veneers & Solids#|#|Composition#||#Metal#|#|Style Elements####Style#||#Contemporary#|#|Style#||#Casual

From this cell i need to remove strings between #|#|"needtoremove"#### only without affecting other strings. I have tried find and replace, finding #|#|*#### and replacing it with #|#|. However its not giving the exact result.

Can anyone help me?

2 个答案:

答案 0 :(得分:1)

另一个解决方案将删除第一个#|#|之间的任何内容和####,事件#||#等

如果您只需要删除#|#|之间的文本和####只有在没有其他## ||的情况下inbetween,我认为最简单的方法是使用正则表达式。

您需要在VBA编辑器的Tools-> References中激活Microsoft VBScript Regular Expressions 5.5库。

将范围(“D166”)更改为您的手机所在的位置。现在的表达式(“#\ |#\ | [A-Za-z0-9&] * ####”)匹配任何以#|#|开头,以####结尾的文本有任何数量的字母数字,&或空间。如果需要,您可以在制动器之间添加其他字符。

Sub remove()
Dim reg As New RegExp
Dim pattern As String
Dim replace As String
Dim strInput As String
strInput = Range("D166").Value
replace = ""
pattern = "#\|#\|[A-Za-z0-9& ]*####"
With reg
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .pattern = pattern
End With


If reg.test(strInput) Then Range("D166").Value = reg.replace(strInput, replace)

End Sub

答案 1 :(得分:0)

像这样。

如果该值在单元格A1中

Dim str As String
Dim i As Integer
Dim i2 As Integer
Dim ws As Excel.Worksheet

Set ws = Application.ActiveSheet

str = ws.Range("A1").Value
i = InStr(str, "#|#|")
i2 = InStr(str, "####")

str = Left(str, i) & Right(str, Len(str) - i2)

ws.Range("A1").Value = str