从单元格

时间:2017-06-30 15:06:26

标签: excel string vba excel-vba checkbox

所以,我一直在努力解决这个问题。任何时候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

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

2 个答案:

答案 0 :(得分:3)

您可以使用“替换”命令来完成所需的操作。只需添加以下代码:

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

答案 1 :(得分: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," - - ","-") ......