Reputation: 2287
I have a cell value like this:
This is a line. /delete words in the area /keep this part
Lets say the cell is A1
, The cell value contains two /
s. I want to use excel VBA to delete the letters between them and change the cell value to:
This is a line. keep this part
Actually I asked a similar question before: Excel VBA: How to remove substrings from a cell?
There I had two different symbols to locate the substring, but here I have two same symbols. Then I dont know how to rewrite the code.
Any help will be appriated. Thanks!
Upvotes: 0
Views: 278
Reputation: 4977
You don't mention whether you would prefer an Excel function or a VBA solution. Both have fairly straightforward answers. In both cases you could keep things simple by using a find function that locates the string index of your search character. In Excel functions it's called Find
and in VBA a very close equivalent is InStr
. You would just find both occurrences of your separator and join the left and right edges of the remaining string.
In Excel, the function could be where "A1" is your cell address:
=LEFT(A1,FIND("/",A1)-1) & RIGHT(A1,LEN(A1)-FIND("/",A1,FIND("/",A1)+1))
Or in VBA, the equivalent would be:
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
Upvotes: 3
Reputation: 9434
How about something like this:
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
Upvotes: 2