VBA仅替换Excel中找到的值的第一个匹配项

时间:2018-07-06 10:06:17

标签: excel vba excel-vba

当我按下替换按钮时,我希望我的代码仅替换excel单元格中值的第一次出现。以下代码的作用是,它同时取代所有出现,而不是一个接一个地出现。但是每次按下按钮时,我都需要一次又一次地执行。 对此有什么解决方案?

Private Sub CommandButton1_Click()
    StrngValue = UserForm1.TextBox2.Text

    If Trim(StrngValue) = "" Then Exit Sub
    For Each wos In ThisWorkbook.Worksheets
        With wos.UsedRange
            Set rng = .Cells.Find(what:=StrngValue)
            If Not rng Is Nothing Then
                Do Until rng Is Nothing
                    Application.Goto Loc, False
                    StrngRepl = Userform2.TextBox1.Text
                    If Not StrngRepl = "" Then
                    rng.Value = StrngRepl
                    Set rng = .FindNext(rng)
                    Else
                    Exit Sub
                    End If
                Loop
            End If
        End With
        Set rng = Nothing

    Next

End Sub

1 个答案:

答案 0 :(得分:3)

也许是这样,但是为什么不使用Excel标准功能

Private Sub CommandButton1_Click()
    StrngValue = UserForm1.TextBox2.Text

    If Trim(StrngValue) = "" Then Exit Sub
    For Each wos In ThisWorkbook.Worksheets
        With wos.UsedRange
            Set Rng = .Cells.Find(what:=StrngValue)
            If Not Rng Is Nothing Then
                'Do Until Rng Is Nothing
                'Application.Goto Loc, False
                StrngRepl = Userform2.TextBox1.Text
                If Not StrngRepl = "" Then
                    Rng.Value = StrngRepl
                    Set Rng = .FindNext(Rng)
                Else
                    Exit Sub
                End If
                'Loop
            End If
        End With
        Set Rng = Nothing

    Next

End Sub