不太清楚如何在math上编写公式

所以我是一个正在学习VBA的学生。 我在课上做得不错,但是如何编程还是有点麻烦的。 对于我所处的问题,我必须把数字放在一列中,并且将它们相乘,除非它们小于或等于零。 下面是一个手工完成结果的例子(与实际问题不一样的数字,这些要简单得多)。

这是我迄今写的。 我有点把这个柱子当作1×10的arrays。

Function multpos(C As Variant) Dim i As Integer Dim MD As Long For i = 1 To 9 MD = C(1, i) * C(1, i + 1) Next i If C(i, 1) > 0 Then C(i, 1) = C(i, 1) Else C(i, 1) = 1 If C(i + 1, 1) > 0 Then C(i + 1, 1) = C(i + 1, 1) Else C(i + 1, 1) = 1 multpos = MD End Function 

虽然MD满足方程式,但它只适用于前两个,然后没有。 直觉上我想做这样的事情

  MD = C(1, i) * C(1, i) Next i 

等等,但这也不是math上正确的。 所以,如果我有

 MD = C(1, i) 

我怎么才能让它乘以下一个值呢? 随意看看我的其他代码,纠正我,因为这可能很容易出错。 感谢您的帮助提前。

像这样的东西应该为你工作。 我试图评论代码的清晰度:

 Public Function PRODUCTIF(ByVal vValues As Variant, ByVal sCriteria As String) As Double Dim vVal As Variant Dim dResult As Double 'Iterate through vValues and evaluate against the criteria for numeric values only For Each vVal In vValues If IsNumeric(vVal) Then If Evaluate(vVal & sCriteria) = True Then 'Value is numeric and passed the criteria, multiply it with our other values 'Note that until a valid value is found, dResult will be 0, so simply set it equal to the first value to avoid a 0 result If dResult = 0 Then dResult = vVal Else dResult = dResult * vVal End If End If Next vVal 'Output result PRODUCTIF = dResult End Function 

你可以这样调用函数: =PRODUCTIF(A1:A10,">0")

你可以利用AutoFiler()方法

 Function multpos(C As Range, criteria As String) Dim MD As Long Dim cell As Range With C.Columns(1) If IsEmpty(.Cells(1, 1)) Then .Cells(1, 1) = "|header|" .AutoFilter Field:=1, Criteria1:=criteria If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then MD = 1 For Each cell In C.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants, xlNumbers) MD = MD * cell.Value Next cell End If If .Cells(1, 1) = "|header|" Then .Cells(1, 1).ClearContents .Parent.AutoFilterMode = False End With multpos = MD End Function 

在你的主要子目录中被利用:

 MsgBox multpos(Range("A1:A10"), ">0")