一起使用replace和find函数可以同时查找多个“点”值

时间:2019-04-05 08:49:24

标签: excel vba

我使用FIND和REPLACE函数在数字中所选单元格的范围内查找点并将其替换为空。

我想实现一个代码以查找多个点,并通过仅执行一次此过程来替换它们。例如:

选择:1.169.499,08->所需输出:1169499,08

选择:111.222,08->所需输出:111222,08

我尝试使用的代码是:

Sub DEtoFR()
'defining the variable z which stores the German number formatting
'defining the variable x which stories the French number formatting

Dim z as Range, x as Variant
Set z = Selection.SpecialCells(xlCellTypeConstants,xlCellTypeConstants)

'Find Counts the Location of the "." character.
'Replace will look for it and replace "." with "". 

For Each x in z
    x.Value = Application.WorksheetFunction.Replace(x.Value, Application.WorksheetFunction.Find(".", x.value), 1, "")
Next x

End Sub

2 个答案:

答案 0 :(得分:1)

您可以使用FindFindNext来执行此操作,而不要循环播放

Sub demo()
    Dim z As Range, c As Range
    ' Declare you range
    Set z = Sheet1.Range("A1:A10")

    With z
        Set c = .Find(".")

        If Not c Is Nothing Then
            Do
                c.Replace what:=".", replacement:=vbNullString
                Set c = .FindNext(c)
            Loop Until c Is Nothing
        End If
    End With
End Sub

评论效率后更新 我使用以下方法生成了1000个带小数的随机数:

Sub CreateDecimals()
    Dim c As Range
    For Each c In Sheet1.Range("A1:A1000")
        c.Value2 = WorksheetFunction.RandBetween(0, 500000) / 100
    Next c
End Sub

然后设置两个测试。第一个命名为FindNextReplace(我的方法),第二个RangeReplace @JvdV方法。

Public Sub FindNextReplace()
    Dim c As Range
    With Sheet1.Range("A1:A1000")
        Set c = .Find(".")

        If Not c Is Nothing Then
            Do
                c.Replace what:=".", replacement:=vbNullString
                Set c = .FindNext(c)
            Loop Until c Is Nothing
        End If
    End With
End Sub

Public Sub RangeReplace()
    With Sheet1.Range("A1:A1000")
        .Replace what:=".", replacement:=vbNullString, searchorder:=xlByColumns, MatchCase:=True
    End With
End Sub

然后我添加了一个计时器函数,可以从两者中调用

Sub TimerTest()
    Dim StartTime As Double
    Dim SecondsElapsed As Double

    StartTime = Timer
    Call RangeReplace

    SecondsElapsed = Round(Timer - StartTime, 2)

    Debug.Print "RangeReplace took:", SecondsElapsed
End Sub

我使用CreateDecimals生成了随机数,然后对其进行了复制,以便可以对两个测试使用相同的值。我运行了一个,替换了TimerTest子中的子名称,并替换了Replace之前的原始值,然后再次运行了。

结果:

Results

您可以看到@JvdV方法显然更有效

答案 1 :(得分:1)

这是另一种处理方式,也许您会学到一些有用的东西:

之前:

enter image description here

代码:

Sub Test()

Dim RNG As Range, LR As Double
With ActiveWorkbook.Sheets(1)
    LR = .Cells(Rows.Count, 1).End(xlUp).Row
    Set RNG = .Range(Cells(1, 1), Cells(LR, 1)).SpecialCells(2)
    RNG.Replace What:=".", Replacement:="", SearchOrder:=xlByColumns, MatchCase:=True
End With

End Sub

结果:

enter image description here