如何计算以分号分隔的字符串中的数字

时间:2017-03-14 09:02:40

标签: excel vba excel-vba

我想在VBA中有多个数字,如:2; 3; 4; 1。 我需要一个VBA程序来计算这些数字。 因此,在一个单元格中,我们有1; 2; 3; 4,在另一个单元格中,所有这些数字都在一起。

我正在考虑一个循环,它接受第一个数字并将其与其余数字分开,然后其余的数字再次进入循环并再次分割一个数字,并且它一直这样做直到所有数字都消失了。只是我不知道如何在VBA中创建类似的东西。 有谁可以帮助我?

3 个答案:

答案 0 :(得分:0)

下面是一个如何通过分隔符拆分字符串并对数组进行计数或求和的示例。

Sub test()
    MsgBox CountInString("2;3;4;1") '= 4
    MsgBox SumInString("2;3;4;1")   '= 10
End Sub

Private Function CountInString(strIn As String) As Long
    Dim arrOut() As String

    arrOut = Split(strIn, ";")
    CountInString = UBound(arrOut) - LBound(arrOut) + 1
End Function

Private Function SumInString(strIn As String) As Double
    Dim arrOut() As String
    arrOut = Split(strIn, ";")

    SumInString = 0
    Dim strItem As Variant
    For Each strItem In arrOut
        SumInString = SumInString + Val(strItem)
    Next
End Function

答案 1 :(得分:0)

你需要的东西 - 假设很多东西,没有错误处理:

Option Explicit

Sub sum()

    Dim i As Integer, j As Integer
    Dim summed As Integer
    Dim nums() As String

    i = 1
    While Sheets(1).Cells(i, 1).Value <> ""

        nums() = Split(Sheets(1).Cells(i, 1).Value, ";")

        summed = 0
        For j = 0 To UBound(nums, 1)

            summed = summed + CInt(nums(j))

        Next j
        Sheets(1).Cells(i, 2).Value = summed
        i = i + 1
    Wend
End Sub

答案 2 :(得分:0)

这可能不是最快捷的方式,但想表现出另一种方式 将您的;转换为+并评估表达式。

所以使用@Peh编写的函数:

Sub test()
    MsgBox SumInString("2;3;4;1")      '= 10
    MsgBox SumInString("2;3;4;1", "*") '= 24
    MsgBox SumInString("2;3;4;1", "-") '= -6
    MsgBox SumInString("2;3;4;1", "/") '= 0.66666667
End Sub

Private Function SumInString(strIn As String, Optional Operator As String = "+") As Double
    Dim sPart As String
    sPart = Replace(strIn, ";", Operator)
    SumInString = Evaluate(sPart)
End Function

您甚至可以扩展为:

Sub test()
    MsgBox SumInString("2;3;4;1", "Count")     '= 4
    MsgBox SumInString("2;3;4;1", "Sum")       '= 10
    MsgBox SumInString("2;3;4;1", "Max")       '= 4
    MsgBox SumInString("2;3;4;1", "Min")       '= 1
    MsgBox SumInString("2;3;4;1")              '= 10
    MsgBox SumInString("2;3;4;1", "*")         '= 24
    MsgBox SumInString("2;3;4;1", "-")         '= -6
    MsgBox SumInString("2;3;4;1", "/")         '= 0.66666667
End Sub

Private Function SumInString(strIn As String, Optional Operator As String = "+") As Double
    Dim sPart As String
    Select Case Operator
        Case "Count", "Sum", "Max", "Min"
            sPart = Operator & "(" & Replace(strIn, ";", ",") & ")"
        Case Else
            sPart = Replace(strIn, ";", Operator)
    End Select
    SumInString = Evaluate(sPart)
End Function