用逗号转换为数字

时间:2015-11-09 09:57:49

标签: excel excel-vba excel-2010 vba

我有下面的代码,当“数字”没有逗号时可正常工作,但当单元格有逗号时,它不会转换为数字。我已尝试将numberformat设为0,或#。## 0等等,但没有任何工作。我该如何解决这个问题呢?

 Sub convert()
        Range("C:C").Select 'specify the range which suits your purpose
        With Selection
            Selection.NumberFormat = "General"
            .Value = .Value
        End With
    End Sub

3 个答案:

答案 0 :(得分:0)

试试这个版本:

Sub convert()
   Dim r As Range

   For Each r In Intersect(Range("C:C"), ActiveSheet.UsedRange)
      With r
         .NumberFormat = "General"
         .Value = Replace(.Value, ",", "")
      End With
   Next r
End Sub

答案 1 :(得分:0)

这是你在尝试的吗?

Sub convert()
    With Columns(3)
        .Replace What:=",", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

        .NumberFormat = "General"
        .Value = .Value
    End With
End Sub

答案 2 :(得分:0)

尝试此代码:它将从

中删除所有字符
    Sub convert()
            Dim MyRange, cell As Range
            Set MyRange = Range("C:C")
            Dim MyNum

            For Each cell In MyRange
            If IsEmpty(cell) Then Exit For
                MyNum = getNumber(cell)
                cell.Value = MyNum
                MyNum = ""
            Next cell

            Range("C:C").Select 'specify the range which suits your purpose
            With Selection
                Selection.NumberFormat = "General"
                .Value = .Value
            End With
        End Sub

这是getNumber函数:

 Public Function getNumber(fromThis As Range) As Double
                'Extract the number from a cell and return it.
                Dim retVal As String
                Dim ltr As String, i As Integer, european As Boolean

                retVal = ""
                getNumber = 0
                european = False


                    If fromThis.Value Like "*.*,*" Then
                    european = True
                End If

                For i = 1 To Len(fromThis)
                    ltr = Mid(fromThis, i, 1)
                    If IsNumeric(ltr) Then
                        retVal = retVal & ltr
               ElseIf ltr = "." And (Not european) And Len(retVal) > 0   hen
                        retVal = retVal & ltr
                    ElseIf ltr = "," And european And Len(retVal) > 0 Then
                        retVal = retVal & "."
                    End If
                Next i
                getNumber = CDbl(retVal)

            End Function