所以我是一名正在学习VBA的学生。我在课堂上表现不错,但仍然对如何编程感到不满。对于我的问题,我必须在一列中取数字并将它们相乘,除非它们小于或等于零。这是一个手工完成结果的示例(与实际问题的数字不同,这些更简单)。
这是我到目前为止所写的内容。我有点将该列视为1 x 10阵列。
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
等等,但这在数学上也不正确。所以,如果我有
MD = C(1, i)
如何让它乘以此处的下一个值?随意查看我的其他代码并纠正我,因为这可能很容易出错。提前感谢您的帮助。
答案 0 :(得分:1)
这样的事情对你有用。为了清晰起见,我试图对代码进行评论:
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")
答案 1 :(得分: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")