[英]Excel VBA: How to remove substrings from a cell (with same beginning and ending symbol)?
我有一个像这样的单元格值:
This is a line. /delete words in the area /keep this part
假设单元格为A1
,单元格值包含两个/
s。 我想使用excel VBA删除它们之间的字母并将单元格值更改为:
This is a line. keep this part
实际上,我之前曾问过类似的问题: Excel VBA:如何从单元格中删除子字符串?
在那里,我有两个不同的符号来定位子字符串,但是在这里,我有两个相同的符号。 然后,我不知道如何重写代码。
任何帮助都将得到赔偿。 谢谢!
您没有提及是希望使用Excel函数还是VBA解决方案。 两者都有相当简单的答案。 在这两种情况下,都可以通过使用find函数来查找搜索字符的字符串索引来简化事情。 在Excel函数中,它称为Find
,在VBA中,它非常接近InStr
。 您只需找到两个出现的分隔符,然后将其余字符串的左右边缘连接起来即可。
在Excel中,该函数可能是“ A1”是您的单元格地址的位置:
=LEFT(A1,FIND("/",A1)-1) & RIGHT(A1,LEN(A1)-FIND("/",A1,FIND("/",A1)+1))
或在VBA中,等效项为:
Public Function TextOutsideDelimeters(txt As String, sep As String) As String
Dim pt1 As Long
Dim pt2 As Long
pt1 = InStr(txt, sep)
pt2 = InStr(pt1 + 1, txt, sep)
TextOutsideDelimeters = Left(txt, pt1 - 1) & _
Right(txt, Len(txt) - pt2)
End Function
这样的事情怎么样:
Option Explicit
Public Sub tmpSO()
Dim i As Long
Dim strTMP As String
Dim strFinal As String
Dim strArray() As String
strTMP = "This is a line. /delete words in the area /keep this part /yet another part to delete / keep this one too / delete me."
strArray = Split(strTMP, "/")
For i = LBound(strArray) To UBound(strArray)
If i Mod 2 = 0 And i <> UBound(strArray) Then
strFinal = strFinal & strArray(i)
End If
Next i
Debug.Print strFinal
End Sub
[A1].Replace "/*/", "", xlPart
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.