仅在textbox vba excel中替换字符串部分

时间:2017-08-23 07:05:41

标签: excel excel-vba vba

大家好想问一下是否有可能替换或删除文本框中的一部分字符串?而不是替换或删除整个字符串,它只会删除它的一部分。该计划将如下程序。

  1. 用户将在文本框示例abc123cd
  2. 中键入字符串或文本 excel单元格中的
  3. 具有默认值abc和cd。我们说abc在A1中,而在A2中是cd。
  4. 然后A1和A2中的默认值将删除abc123cd中的abc和cd。输出将在同一文本框中为123。它表示在abc123cd之前,单击commnad按钮后,结果将仅在同一文本框中为123。
  5. 以下是我的示例vba程序。但显然我无法找到解决问题的方法以满足我的要求。希望有人可以提供帮助。谢谢。

    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
    

1 个答案:

答案 0 :(得分:0)

如何只更改文本框内的值?例如:

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