字符处理——字符替换

2020-07-28 14:19:57 浏览数 (1)

字符替换在Excel使用过程中应该比较常用,比如清除不可见字符、替换某些特殊字符等。

效果:

创建两个Ribbon菜单按钮,首先在customUI.xml中增加代码:

代码语言:javascript复制
        <menuSeparator id="rbSepString01" title="================="/>

        <button id="rbbtnClean" label="清除不可见字符" onAction="rbbtnClean" imageMso="QueryBuilder"/>
        <button id="rbbtnRepBrackets" label="替换中文括号" onAction="rbbtnRepBrackets"/>

回调函数:

代码语言:javascript复制
Sub rbbtnClean(control As IRibbonControl)
    Call MRange.Clean
End Sub
Sub rbbtnRepBrackets(control As IRibbonControl)
    Call MRange.RepBrackets
End Sub

函数实现:

代码语言:javascript复制
Sub RepBrackets()
    Dim rng As Range, selectRng As Range
    Dim str As String
    
    '确保选中的是单元格
    If TypeName(Selection) = "Range" Then
        Set selectRng = Selection
        
        For Each rng In selectRng
            str = VBA.CStr(rng.Value)
            str = VBA.Replace(str, "(", "(")
            str = VBA.Replace(str, ")", ")")
            rng.Value = str
        Next rng
    End If
    
    Set rng = Nothing
    Set selectRng = Nothing
End Sub

Sub Clean()
    Dim rng As Range, selectRng As Range
    
    '确保选中的是单元格
    If TypeName(Selection) = "Range" Then
        Set selectRng = Selection
        
        For Each rng In selectRng
            '直接调用Excel内置的Clean函数
            rng.Value = Application.WorksheetFunction.Clean(rng.Value)
        Next rng
    End If
    
    Set rng = Nothing
    Set selectRng = Nothing
End Sub

注意:Excel内置的Clean函数可以清除ASCII字符为1-31的不可见字符,但是129之后的字符是不能清除的。

另外可以根据自己实际工作需要,实现一些用的上的字符替换功能。

0 人点赞