Replace 删除、替换函数精解示例

时间:2023-03-09 01:04:20
Replace 删除、替换函数精解示例

'*************************************************************************

'**模 块 名:Replace函数精解示例
'**说    明:蓝凤凰设计商城 浴火凤凰-郭卫 | 蓝凤凰-魔灵 | 郭卫-icecept
'**创 建 人:浴火凤凰-郭卫
'**日    期:2015年10月11日  12:00:13
'**修 改 人:浴火凤凰-郭卫
'**日    期:
'**描    述:QQ:493405998 | 微信\旺旺:icecept
'**版    本:V1.0.0 | http://blog.sina.com.cn/icecept
'*************************************************************************
Option Explicit
'Replace: 将字符串中的某些特定字符串替换为其他字符串
'格式:
'P = Replace$(原字符串, 被替换的字符串, 用作替换的字符串,[起始位置],[替换数量],[比较方式])
'特别注意:此函数的起始位置是几,输出时就从起始位置的位置开始到结尾输出,起始位置前的字符被截断。
'所以要想修改起始字符大于一且要保留起始位置前的字符,必须用left把起始位置之前的字符再获取一次。
'Left(原字符串,起始位置-1) & Replace$(原字符串, 被替换的字符串, 用作替换的字符串,[起始位置],[替换数量],[比较方式])
Private Sub Command1_Click()
    Dim startc As Integer, rcount  As Integer
    '********************** 第一种用法 *********************** 无条件全部替换
    Debug.Print Replace$(Text1.Text, "A", "x")
    '********************** 第二种用法 *********************** 从第一位开始只替换3次
    Debug.Print Replace$(Text1.Text, "A", "x", , 3)
    '********************** 第三种用法 *********************** 从前面算起第5位开始全部替换
    Debug.Print Left$(Text1.Text, 4) & Replace$(Text1.Text, "A", "x", 5)
    '********************** 第四种用法 *********************** 从前面算起第6位开始替换5次
    Debug.Print Left$(Text1.Text, 4) & Replace$(Text1.Text, "A", "x", 6, 5)
    '********************** 第五种用法 *********************** 不分大小写的替换
    Debug.Print Replace$(Text1.Text, "a", "x", , , vbTextCompare)
    '********************** 第六种用法 *********************** 分大小写的替换
    Debug.Print Replace$(Text1.Text, "a", "x", , , vbBinaryCompare)
End Sub
'替换或删除相同字符
Private Sub Command2_Click()
    Dim a As String, b As String, c As String
    Dim i As Integer
    a = "0123456789"
    b = "346"
    For i = 1 To Len(b)
        '分别取子字符串中的一个字符删除原字符串中的字符
        a = Replace$(a, Mid$(b, i, 1), vbNullString)
    Next
    Debug.Print a
    '输出结果为:  0125789
End Sub
'替换或删除指定字符
Private Sub Command3_Click()
    Dim x As String
    x = "VB is very good"
    Debug.Print Replace$(x, "good", "nice")
    '输出结果为:  "VB is very nice"
End Sub
Private Sub Command4_Click()
    Dim strA As String
    Dim strB() As String
    Dim strC As String
    Dim strD As String
    strA = "aa               bb                cc"
    strB = Split(strA, Space$(1))
    strC = Join(strB, vbNullString)
    '----------------------------------------
    Do While InStr(strA, "  ") <> 0
        strA = Replace$(strA, "  ", " ")
    Loop
    Debug.Print strA, strC      '此行输出 aa bb cc      aabbcc
    Debug.Print Replace$(strA, Space$(1), Empty)   '此行输出aabbcc
End Sub