Search code examples
excelvbauserform

How can I add text to a textbox before a certain occurrence of a character?


Right now, I have a text box adding text indicators around added text. For instance, when someone writes, "He is a dad" it comes out as "NOTE (SALE): He is a dad (8/27/2024)(5:44:00pm)(3608)" using this code:

If Not Mark1.NEWCALLHISTORYTEXTBOX.Value = "" And Not InStr(Mark1.NEWCALLHISTORYTEXTBOX.Value, "NOTE ") > 0 Then Mark1.NEWCALLHISTORYTEXTBOX.Value = "NOTE (" & Mark1.NEWDISPODROPDOWN.Value & "): " & Mark1.NEWCALLHISTORYTEXTBOX.Value & " (" & Date & ")" & "(" & Time & ")" & "(" & Mark1.REPNUMBERTEXTBOX.Value & ")."

My issue is I want to be able to change certain parts of the textbox when something else on the userform is changed without changing the entire note around it.

For instance, when the value in "Mark1.NEWDISPODROPDOWN.Value" changes, I want it to update just that part in the string without changing anything else.

I don't know to specify just that area and am having trouble figuring it out.


Solution

  • If I were right, SALE is coming from Mark1.NEWDISPODROPDOWN.Value in your sample. Provided code update 'SALE' to 'NewText'.

    Sub demo()
        Dim sTxt, sNewTxt, arrText1, arrText2
        sTxt = "NOTE (SALE): He is a dad (8/27/2024)(5:44:00pm)(3608)"
        arrText1 = Split(sTxt, ")")
        arrText2 = Split(arrText1(0), "(")
        arrText2(1) = "NewText" ' Mark1.NEWDISPODROPDOWN.Value
        arrText1(0) = Join(arrText2, "(")
        sNewTxt = Join(arrText1, ")")
        Debug.Print sNewTxt
    End Sub
    
    

    If it always has the same pattern NOTE (xx):.., the code could be simpler.

    Sub demo()
        Dim sTxt, sNewTxt, sUpdateText
        sTxt = "NOTE (SALE): He is a dad (8/27/2024)(5:44:00pm)(3608)"
        sUpdateText = "NewText" ' Mark1.NEWDISPODROPDOWN.Value
        sNewTxt = "NOTE (" & sUpdateText & Mid(sTxt, InStr(sTxt, ")"))
        Debug.Print sNewTxt
    End Sub
    

    Output

    NOTE (NewText): He is a dad (8/27/2024)(5:44:00pm)(3608)