2

基本上我想做的是用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

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

4

1 回答 1

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
于 2012-06-13T08:48:16.083 回答