简体   繁体   中英

replace string part only in textbox vba excel

Hi all just want to ask if it is possible to replace or delete a part of string in textbox? instead of replacing or removing the whole string it will just remove part of it only . The program will be as below procedure.

  1. A user will key in string or text in a textbox example abc123cd
  2. in an excel cells have a default value of abc and cd . Let we say abc is in A1 and cd in A2.
  3. Then those default value in A1 and A2 will remove abc and cd in abc123cd. The output will be 123 in the same textbox. it means before it is abc123cd , after clicking commnad button the result will be 123 only in the same textbox.

Below is my sample vba program. But obviously I cannot find the way to fix the issue just to suit my requirements. Hopefully someone can help. Thank you.

Private Sub CommandButton1_Click()
    Dim myLastRow As Long
    Dim myRow As Long
    Dim myFind As String
    Dim myReplace1 As String
    Dim myReplace2 As String
    Dim sExportFolder, sFN
    Dim rArticleName As Range
    Dim rDisclaimer As Range
    Dim oSh As Worksheet
    Dim oFS As Object
    Dim oTxt As Object

    'Specify name of Sheet with list of replacements
    Set myReplaceSheet = Sheets("Sheet2")

    'Assuming list of replacement start in column A on row 2, find last entry in list
    myLastRow = myReplaceSheet.Cells(Rows.Count, "A").End(xlUp).Row

    Application.ScreenUpdating = False

    'Loop through all list of replacments
    For myRow = 2 To myLastRow
        'Get find and replace values (from columns A and B)
        myFind = myReplaceSheet.Cells(myRow, "A")
        myReplace1 = myReplaceSheet.Cells(myRow, "B")

        'Start at top of data sheet and do replacements
        myDataSheet.Activate
        Range("A2").Select

        'Ignore errors that result from finding no matches
        On Error Resume Next

        'Do all replacements 
        With TextBox1
            .Replace What:=myFind, Replacement:=myReplace1, LookAt:=xlPart, _
              SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
              ReplaceFormat:=False
        End With
    Next myRow
End Sub

How about just changing the value inside the textbox? For example:

TextBox1.Value = VBA.Replace(TextBox1.Value, myFind, myReplace1)

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