VBA替换功能问题

时间:2017-06-09 07:54:45

标签: vba excel-vba excel

我的VBA的REPLACE功能有问题。 例如,我在一张纸上并使用CTRL + H替换所有“。”对“,”,它的效果很好。 但是,当我尝试使用宏时,我会遇到值>的问题。比1

  • 0.8 ---> 0,8
  • 0.9 ---> 0,9
  • 1.09978063783 ---> 109978063783

以下是代码:

Rows("10:10").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False, MatchByte:=False

3 个答案:

答案 0 :(得分:0)

这会为你做到这一点吗?

Sub Test()
Dim i As Integer, rng As Range, cell As Range

For i = 10 To 1000
Set rng = Rows(i)
    rng.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False, MatchByte:=False
Next i
End Sub

答案 1 :(得分:0)

Try this code:

Sub DotsToCommas()
    Dim Txt As String, Col As Long
    For Col = 1 To ActiveSheet.Columns.Count
        Txt = CStr(ActiveSheet.Cells(10, Col).Value)
        If Txt = "" Then
            Exit Sub
        End If
        Txt = Replace(Txt, ".", ",")
        ActiveSheet.Cells(10, Col).Value = Txt
    Next
End Sub

It will take a bit more time, as it does a loop through all cells until it finds a empty one.

答案 2 :(得分:0)

This should do it:

Sub replaceDecimalPoint()

Dim lastRowNum As Long
Dim lastColNum As Long
Dim startRow As Long
Dim tempVal As String


lastRowNum = Cells(Rows.Count, 1).End(xlUp).Row
lastColNum = Cells(10, Columns.Count).End(xlToLeft).Column

startRow = 10 'Change this if row start number is required to be changed from 10

Dim rangeArray As Variant
rangeArray = Range(Cells(startRow, 1), Cells(lastRowNum, lastColNum)).Value 'Assuming to start at row 10 as you have used Row 10 (And Column A) - If NOT,     Change startRow

For r = startRow To lastRowNum 'Assuming to start at row 10 as you have used Row 10 - If NOT, Change startRow

    For c = 1 To lastColNum
        tempVal = rangeArray(r - (startRow - 1), c)
        If CDbl(tempVal) > 1 Then
            tempVal = CStr((tempVal * (10 ^ (Len(tempVal) - 1))))
        End If

        rangeArray(r - (startRow - 1), c) = Replace(CStr(tempVal), ".", ",")
    Next c

Next r

Range(Cells(startRow, 1), Cells(lastRowNum, lastColNum)).Value = rangeArray

End Sub