【问题标题】:Remove Duplicates from String in Cell从单元格中的字符串中删除重复项
【发布时间】:2017-12-04 14:20:30
【问题描述】:

所以,我一直在努力解决这个问题。任何时候 CheckBox3 和 CheckBox6 都被选中,当我只需要一个时,它会复制“-”。我尝试使用 Len 以及一个数组来遍历字符串以删除重复项,但对我来说也没有这个技巧;我可能只是做错了,因为我还是 VBA 的初学者。无论如何,这是我的代码:

Private Sub btnOK_Click()
Dim strText As String, strDelimiter As String

strDelimiter = " "

If cbxDD.Value = "DD" Or cbxMM.Value = "MM" Then
    MsgBox "Please enter both a month and date.", , "Invalid Entry"
    Exit Sub
End If

If CheckBox4.Value = True Then strText = strText & "DR" & strDelimiter
If CheckBox5.Value = True Then strText = strText & "C" & strDelimiter
If CheckBox2.Value = True Then strText = strText
If CheckBox1.Value = True Then strText = strText & ChrW(8730) & strDelimiter
If CheckBox3.Value = True Then strText = strText & "-" & strDelimiter
If CheckBox6.Value = True Then strText = strText & "- CP" & strDelimiter
If CheckBox7.Value = True Then strText = strText & "Cancelled" & strDelimiter
If CheckBox9.Value = True Then strText = strText & "TS" & strDelimiter
If CheckBox8.Value = True Then strText = strText & "Lost" & strDelimiter

If Len(strText) > 0 = True Then
    strText = Left(strText, Len(strText) - Len(strDelimiter)) 'remove trailing delimiter
    ActiveCell.Value = cbxMM.Value & "/" & cbxDD.Value & " " & txtCode.Value & " " & strText
    Unload Me
Else
    MsgBox "No Status selected.", , "Invalid Entry"
End If

If CheckBox2.Value Or CheckBox4.Value Or CheckBox5.Value = True Then
    ActiveCell.Value = "x" & ActiveCell.Value
Else
    ActiveCell.Value = ActiveCell.Value
End If    
End Sub

任何帮助都会很棒!谢谢。

【问题讨论】:

    标签: string vba excel checkbox


    【解决方案1】:

    您可以使用替换命令来完成您需要的操作。只需添加此代码:

       strtext = Replace(strtext, "--", "-")
    

    【讨论】:

    • 啊!我在If 声明上花了太多时间,只是在重写那部分后才意识到同样的事情......快速思考:D
    • 哇。没想到这么简单!谢谢!
    【解决方案2】:

    如果我正确理解代码,也许可以试试这个(将 If Checkbox3.Value ... 和 If CheckBox6.Value... 这两行替换为:

    If CheckBox6.Value = True and Checkbox3.Value = False Then 
        strText = strText & "- CP" & strDelimiter
    ElseIf CheckBox3.Value = True and CheckBox6.Value = False Then 
        strText = strText & "-" & strDelimiter
    ElseIf CheckBox3.Value = True and CheckBox6.Value = True Then
        strText = strText & "0 CP" & strDelimiter
    

    或者,实际上,首先在整个 If 块之后,尝试

    strText = Replace(strText,"--","-")

    或者如果不是两个- 背靠背,只需调整第二个参数,也许应该是strText = Replace(strText,"- -","-") 或...strText," - - ","-")...

    【讨论】:

    • 谢谢!我会给你一个赞成票,但我还没有这样做的特权。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 2014-04-03
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多