【问题标题】:Excel VBA: How to remove substrings from a cell (with same beginning and ending symbol)?Excel VBA:如何从单元格中删除子字符串(具有相同的开始和结束符号)?
【发布时间】:2016-08-21 10:43:16
【问题描述】:

我有一个像这样的单元格值:

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: How to remove substrings from a cell?

我有两个不同的符号来定位子字符串,但在这里我有两个相同的符号。那我就不知道怎么改代码了。

任何帮助都会得到帮助。谢谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您没有提到您更喜欢 Excel 函数还是 VBA 解决方案。两者都有相当简单的答案。在这两种情况下,您都可以通过使用查找搜索字符的字符串索引的查找函数来保持简单。在 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
    

    【讨论】:

      【解决方案2】:

      这样的事情怎么样:

      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
      

      【讨论】:

        【解决方案3】:
        [A1].Replace "/*/", "", xlPart
        

        【讨论】:

          猜你喜欢
          • 2015-06-13
          • 2023-03-27
          • 2017-07-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          相关资源
          最近更新 更多