简体   繁体   中英

String manipulation VBA Excel

I might have been up too late but I cant figure out how to do basic string manipulation.

I am trying to get a text box to add the value form a label after clicking a checkbox, and then remove that string when you uncheck the checkbox, no matter where that string is in the textbox. I clear the label after adding it so that the user cannot repeatedly add the string.

So, after trying a few different things, I still cant figure this out. This version eds up having the string default to "". I tried to bounce the value around but still ends up not working.

Any pointers would be nice, thanks

Private Sub CheckBox1_Click()
    Dim chxbox1cmt As String
    Dim TxtString As String
    Dim myString As String
    chxbox1cmt = Label1.Caption

    If CheckBox1.Value = True Then
        myString = chxbox1cmt
        TxtString = TxtString + myString
        TextBox1.Value = TxtString
        myString = Left(InStr(TxtString, Len(myString)), Len(myString))
        Label1.Caption = vbNullString
    End If

    If CheckBox1.Value = False Then
        TxtString = TxtString - Left(InStr(myString, myString), myString)
        TextBox1.Value = TxtString
    End If
End Sub

If I understand the question correctly, you need to move TxtString to a module level. You currently have it declared as a local variable, so any value you put in it just goes away after it leaves scope (at End Sub ).

Private TxtString As String

Private Sub CheckBox1_Click()
    Dim chxbox1cmt As String
    Dim myString As String
    chxbox1cmt = Label1.Caption

    If CheckBox1.Value = True Then
        myString = chxbox1cmt
        TxtString = TxtString + myString
        TextBox1.Value = TxtString
        myString = Left$(InStr(TxtString, Len(myString)), Len(myString))
        Label1.Caption = vbNullString
    Else
        TxtString = TxtString - Left$(InStr(myString, myString), myString)
        TextBox1.Value = TxtString
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM