如果单元格包含3个特定字符,请删除这些字符,否则添加这些字符

时间:2015-05-07 13:46:43

标签: excel vba excel-vba

Sub Test()
Dim c As Range
Dim d As Range

If InStr(1, c, "+") Then
For Each c In Selection
c.Replace What:="(", Replacement:="", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
c.Replace What:=")", Replacement:="", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
c.Replace What:="+", Replacement:="", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Next c
End If

For Each c In Selection
If c.Value <> "" Then c.Value = "+" & c.Value
c.Replace " ", " +"
Next

For Each d In Selection
If d.Value <> "" Then d.Value = "(" & d.Value & ")"
Next d
End Sub

我正在尝试创建一个切换,因为我的加载项无法显示,我似乎无法弄清楚如何将它放在加载项屏幕中。搜索高低,其他似乎有相同的问题。所以,除了那个奇妙的问题之外,我似乎无法弄清楚如何使用按钮以某种方式创建一个切换到插件。

我想要的只是说:

如果您发现“+”或“(”或“)”,则从单元格中删除,否则如果您找不到单元格中的那些字符,在特定位置添加。所以这应该是场景:

  

原始字符串:Hello World

  单击一次:(+ Hello + World)

  点击两次:Hello World

请帮助我在这里发疯。

谢谢大家!

2 个答案:

答案 0 :(得分:0)

我认为你错误地放置了End If,所以每当你加入角色时,即使它们已经存在于第一位!

你也错放了For each c,因此“c”未设置且无法使用!

采取增加代码的习惯,使其更具可读性,您将不会遇到这类问题! ;)

尝试一下(我添加了其他字符测试):

    Sub Test()
Dim c As Range

For Each c In Selection
    If InStr(1, c, "+") Or InStr(1, c, "(") Or InStr(1, c, ")") Then
        c.Replace What:="(", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        c.Replace What:=")", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        c.Replace What:="+", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    Else
            If c.Value <> "" Then c.Value = "+" & c.Value
            c.Replace " ", " +"

            If c.Value <> "" Then c.Value = "(" & c.Value & ")"
    End If
Next c
End Sub

答案 1 :(得分:0)

首次尝试对其值运行函数时,尚未定义

Sub Test()
Dim c As Range
Dim d As Range

If InStr(1, c, "+") Then
For Each c In Selection

经过测试的工作变体,也有所优化。

Sub Test()
Dim c As Range

For Each c In Selection
    If InStr(1, c, "+") Then 'if it has a plus sign
        c.Value2 = Replace(Replace(Replace(c.Value2, "(", ""), ")", ""), "+", "") 'replaces (, ) and +
        Else 'if it doesn't have a plus sign
        If c.Value2 <> "" Then 'if it's not zero length
            c.Value2 = "(+" & Replace(c.Value2, " ", " +") & ")" 'replaces " " with " +" and puts the value in brackets, after the first bracket comes a plus sign as per your example
        End If
    End If
Next c
End Sub