VBA用于在一个范围内乘以奇数

时间:2018-04-06 17:48:08

标签: excel vba excel-vba

我是excel VBA的新手,并尝试编写一个VBA函数来乘以一个范围内的奇数。我使用SumEvenNumbers(rng)函数作为起点,但我无法弄清楚如何将它变成我想要的。 这就是我到目前为止所做的:

Function SumEvenNumbers(rng)
    SumEvenNumbers = 0
    Counter = 0
    Numeven = 0
    For Each Cel In rng
        Counter = Counter + 1
            If Cel.Value Mod 2 = 0 Then
                Numeven = Numeven + 1
                SumEvenNumbers = SumEvenNumbers + Cel.Value
            End If
        Debug.Print Counter, Numeven, SumEvenNumbers
    Next Cel
End Function

'multiply odd numbers
Function MultiplyOddNumbers(rng)
    MultiplyOddNumbers = 0
    Counter = 0
    MultOdd = 0
    For Each Cel In rng
        Counter = Counter + 1
            If Cel.Value Mod 2 = 1 Then
                MultiplyOddNumbers = MultiplyOddNumbers * Cel.Value
            End If
        Debug.Print Counter, MultOdd, MultiplyOddNumbers
    Next Cel
End Function

1 个答案:

答案 0 :(得分:1)

MultiplyOddNumbers始终为0,因为您从未为其分配过不同的值。你只是每次将单元格值乘以0。

更改

MultiplyOddNumbers = 0

MultiplyOddNumbers = 1

并且您的代码将按照需要运行