Excel VBA Selection.replace不替换所有内容

时间:2012-06-13 07:44:54

标签: excel vba excel-vba

基本上我要做的是用VBA代码模仿替换按钮。我使用以下代码:

Private Sub CommandButton1_Click()
    Blad1.Activate
    Blad1.Cells.Select
    Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

这取代了所有的点,但在某些情况下,它用空格而不是逗号替换点。这是为什么?

1 个答案:

答案 0 :(得分:2)

试试这个

Sub Sample()
    Dim oRange As Range, aCell As Range, bCell As Range
    Dim ws As Worksheet
    Dim ExitLoop As Boolean
    Dim SearchString As String, FoundAt As String
    On Error GoTo Err
    Set ws = Blad1
    Set oRange = ws.Cells

    oRange.NumberFormat = "@"

    SearchString = "."
    Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        Set bCell = aCell
        Do While InStr(1, aCell.Formula, ".") > 0
            aCell.Formula = Replace(aCell.Formula, ".", ",")
        Loop
        Do While ExitLoop = False
            Set aCell = oRange.FindNext(After:=aCell)

            If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                Do While InStr(1, aCell.Formula, ".") > 0
                    aCell.Formula = Replace(aCell.Formula, ".", ",")
                Loop
            Else
                ExitLoop = True
            End If
        Loop
    End If
    Exit Sub
Err:
    MsgBox Err.Description
End Sub
相关问题