如何对两个列值求和并进行平均,并在另一列中显示结果

时间:2014-01-30 16:59:19

标签: excel excel-vba if-statement sum vba

我需要在Excel VBA中合并4个文件。到目前为止,我设法做到了这一点(实际工作表中的更多数据):

 F          P           L           V              W
80          50       Completed   Incomplete   
80          70       Completed   Incomplete   
80          70       Completed   Completed   
80          70       Completed   Completed   
30          20       Completed   Completed
80          50       Completed   Incomplete   
80          70       Completed   Incomplete   
80          70       Completed   Completed   
80          70       Completed   Completed   
30          20       Completed   Completed

为了在W列中获取“已完成”的值,我需要满足以下条件:

  • LV必须为“已完成”
  • F + P的平均分数必须大于或等于70%

否则,列W将为“不完整”。

以下是我编写的代码,它不会计算列FP的平均分数:

Sub OverallStatus()

Dim x As Long

For x = 1 To 65536
    If InStr(1, Sheet1.Range("$L$" & x), "Completed") And InStr(1, Sheet1.Range("$V$" & x), "Completed") > 0 Then
        Sheet1.Range("$W$" & x) = Sheet1.Range("$W$" & x) & "Completed"
    End If
Next

End Sub

使用上述代码得到的结果不准确,因为它没有检查第二个条件(FP的平均分数):

     F          P           L           V              W
    80          50       Completed   Incomplete   
    80          70       Completed   Incomplete   
    80          70       Completed   Completed      Completed
    80          70       Completed   Completed      Completed 
    30          20       Completed   Completed      Completed
    80          50       Completed   Incomplete   
    80          70       Completed   Incomplete   
    80          70       Completed   Completed      Completed 
    80          70       Completed   Completed      Completed
    30          20       Completed   Completed      Completed

如何总结列FP的平均值,并使用结果在W列中显示正确的文字?

2 个答案:

答案 0 :(得分:0)

这段代码怎么样(感谢lastrow代码的@SiddharthRout):

Sub OverallStatus()

    Dim x As Long
    Dim lastrow As Long

    With sheet1
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
             lastrow = .Cells.Find(What:="*", _
                         After:=.Range("A1"), _
                         Lookat:=xlPart, _
                         LookIn:=xlFormulas, _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlPrevious, _
                         MatchCase:=False).Row
        Else
            lastrow = 1
        End If
        For x = 1 To lastrow
            If .Range("L" & x) = "Completed" And .Range("V" & x) = "Completed" _
                And .Range("F" & x) + .Range("P" & x) > 140 Then
                .Range("W" & x) = "Completed"
            Else
                .Range("W" & x) = "Incomplete"
            End If
        Next
    End With

End Sub

首先我发现最后一个非空行lastrow而是循环直到65536.然后我添加了And .Range("F" & x) + .Range("P" & x) > 140 Then,这意味着平均(Fx+Px)/2 > 70或等于(Fx+Px)>140

如果您的数据以百分比格式存储,则应将140更改为1.4

答案 1 :(得分:0)

如果这是一次性工作,那么Excel公式将更合适。

将Excel公式粘贴到单元格W2中。

=IF(AND(L2="Completed",V2="Completed",AVERAGE(F2,P2)>70),"Completed","Incomplete")

然后根据需要将细胞复制到其他细胞中。