VBA中的嵌套条件

时间:2019-02-20 06:14:35

标签: excel vba

我是excel和VBA的新手,所以为愚蠢的问题或错误表示歉意。

我在sheet2中有2000个excel数据,在sheet 1中有数据要求

Sample image please check this

我需要知道有多少以INC和优先级P2 P3开头的票证,以及有多少以SR开头的票证。还有其中几个处于关闭状态,还有几个处于活动状态。

Sub US_Data()
Dim z As Long
Dim C As Range

z = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row
For Each C In Sheet2.Range(Sheet2.Cells(2, 1), Sheet2.Cells(z, 1))
  If Left(C.Value, 3) = "INC" Then
    Sheet1.Cells(8, 6) = Sheet1.Cells(8, 6) + 1

  End If
Next C
End Sub

谢谢

2 个答案:

答案 0 :(得分:1)

Sub US_Data()
Dim z As Long
Dim HighCount as Long
Dim ModerCount as Long
Dim LowCount as Long
Dim OpenCount as Long
Dim ClosedCount as Long
Dim C As Range

z = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row

For Each C In Sheet2.Range(Sheet2.Cells(2, 1), Sheet2.Cells(z, 1))
    If Left(C.Value, 3) = "INC" Then
        If C.Offset(0,1).Value = "2 - High" Then HighCount = HighCount + 1
        If C.Offset(0,1).Value = "3 - Moderate" Then ModerCount = ModerCount + 1
        If C.Offset(0,1).Value = "4 - Low" Then LowCount = LowCount + 1
        If C.Offset(0,2).Value = "Closed" Then ClosedCount = ClosedCount + 1
        If C.Offset(0,2).Value = "Open" Then OpenCount = OpenCount + 1
    End If
Next C

MsgBox "I have counted " & HighCount & " times High, " & ModerCount & " times Moderate, " & LowCount & " times Low, and respectively " & OpenCount & " and " & ClosedCount & " open and closed instances.", vbOkOnly, "FYI"

Sheet1.Cells(8, 6) = HighCount
End Sub

这是一种实现方式,您可以用这些变量填充必要的单元格。

答案 1 :(得分:1)

为什么要完全使用VBA?这可以通过简单的公式完成。如果您不想使用数据透视表,请手动创建标题(屏幕截图中的蓝色),然后将此公式放入单元格H3中,上下复制。

=COUNTIFS($A:$A,$G3&"*",$B:$B,H$1,$C:$C,H$2)

enter image description here

根据需要更改布局。关键是您不需要VBA。公式比使用VBA重新发明CountIfs要快得多。