如何计算单元格中的数值

时间:2016-01-27 22:26:39

标签: excel excel-vba vba

我在单元格中有值。

1,2,4,45,64,Jan. Ans: 5

我想只计算细胞中的数字。 有可能吗?

2 个答案:

答案 0 :(得分:0)

您还可以在UDF中使用split函数:

Function CountNumbers(R As Range) As Integer
  Dim values, value As Variant
  Dim result As Integer

  values = Split(R.Text, ",")
  result = 0

  For Each value In values
    If IsNumeric(value) Then
      result = result + 1
    End If
  Next value

  CountNumbers = result

End Function

从此处,您可以在另一个Excel单元格中将其称为:

=CountNumbers(A1)

答案 1 :(得分:-1)

以下是我的回答:

Sub countingNumbers()
    Dim c As Range
    Dim L As Long
    Dim s As String
    Dim tmp
    Dim i
    Dim y
    Set c = Range("A1") 'Imagine in A1 is this: "RDFY2372784GDTD2GV3G3G3V3"
    L = Len(c.Value) 'to store the len of the string
    s = c.Value 'to store the string
    y = 0 'the index of the numbers
    For i = 1 To L
        tmp = Left(Right(s, i), 1) 'to take just one letter at the time
        If Asc(tmp) < 57 And Asc(tmp) > 48 Then
        'if is a number ASC() returns the ASCII code of that number
        'and increase y one by one || that is number by number
            y = y + 1
        End If
    Next i
    Range("B2").Value = y 'store the counting in B2
End Sub


Part of the ASCII Table:
+------------+-----------+
| ASCII Code | Character |
+------------+-----------+
|         48 | 0         |
|         49 | 1         |
|         50 | 2         |
|         51 | 3         |
|         52 | 4         |
|         53 | 5         |
|         54 | 6         |
|         55 | 7         |
|         56 | 8         |
|         57 | 9         |
|         64 | @         |
|         65 | A         |
|         66 | B         |
|         67 | C         |
|         68 | D         |
|         69 | E         |
|         70 | F         |
|         71 | G         |
|         72 | H         |
|         73 | I         |
|         74 | J         |
+------------+-----------+

您可以在这里查看ASCII表格