我在循环列中并计算每行在另一列中出现的次数。这个工作一次,显示正确的计数。但是在随后的情况下,它只对所有行显示为零。我逐步完成了代码,计数器值不会更新。如果有人看一下,我很感激。
Sub count_tic_types()
Dim ticCountGraph As Worksheet
Dim CWData As Worksheet
'' Row count for ticCountGraph.
Dim i As Integer
'' Row count for CWData
Dim j As Integer
Dim ticCount As Integer
Dim ticAlert As Integer
Set ticCountGraph = Worksheets("ticCountGraph")
Set CWData = Worksheets("CWData")
For i = 1 To 9
'' Start the counters fresh for each new row. Ensures that
'' there's no double counting.
ticCount = 0
ticAlert = 0
'' Loop through entire target column to count the number of
'' matches there.
For j = 2 To CWData.Range("A2").End(xlDown).Row
'' Want to count values that have been Closed.
If Range("I" & j).Value = "Closed" Then
'' Increment if there are mathces.
If CWData.Range("J" & j).Value = ticCountGraph.Range("A" & i).Value Then
ticCount = ticCount + 1
'' Count blank values separately.
ElseIf IsEmpty(CWData.Range("J" & j)) Then
ticAlert = ticAlert + 1
End If
End If
Next
If ticCountGraph.Range("A" & i).Value = "Alerts" Then
ticCountGraph.Range("B" & i).Value = ticAlert
Else
ticCountGraph.Range("B" & i).Value = ticCount
End If
Next
End Sub
j
将遍历的列,并计算出现次数
匹配上图中的每一行。
答案 0 :(得分:2)
我现在明白了。问题可能是带有未指定工作表的Range("I"&j).Value
。在我用CWData
指定它之后,它就可以了。
课程:使用不同工作表中的范围时,请确保使用正确的工作表名称为所有函数添加前缀。
For i = 2 To 10
'' Start the counters fresh for each new row. Ensures that
'' there's no double counting.
ticCount = 0
ticAlert = 0
For j = 2 To CWData.Range("A2").End(xlDown).Row
'' THIS IS THE PART THAT REQUIRED WORKSHEET NAME.
If CWData.Range("I" & j).Value <> ">Cancelled" Then
If CWData.Range("J" & j).Value = ticCountGraph.Range("A" & i).Value Then
ticCount = ticCount + 1
ElseIf IsEmpty(CWData.Range("J" & j)) Then
ticAlert = ticAlert + 1
End If
End If
Next j
If ticCountGraph.Range("A" & i).Value = "Alerts" Then
ticCountGraph.Range("B" & i).Value = ticAlert
Else
ticCountGraph.Range("B" & i).Value = ticCount
End If
Next i
答案 1 :(得分:1)
Sub count_tic_types()
Dim ticCountGraph As Worksheet
Dim CWData As Worksheet
'' Row count for ticCountGraph.
Dim i As Integer
'' Row count for CWData
Dim j As Integer
Dim ticCount As Integer
Dim ticAlert As Integer
Set ticCountGraph = Worksheets("ticCountGraph")
Set CWData = Worksheets("CWData")
For i = 1 To 9
'' Start the counters fresh for each new row. Ensures that
'' there's no double counting.
ticCount = 0
ticAlert = 0
For j = 2 To CWData.Range("A2").End(xlDown).Row
If Range("I" & j).Value = "Closed" Then
If CWData.Range("J" & j).Value = ticCountGraph.Range("A" & i).Value Then
ticCount = ticCount + 1
ElseIf IsEmpty(CWData.Range("J" & j)) Then
ticAlert = ticAlert + 1
End If
End If
Next j ' forgot j
If ticCountGraph.Range("A" & i).Value = "Alerts" Then
ticCountGraph.Range("B" & i).Value = ticAlert
Else
ticCountGraph.Range("B" & i).Value = ticCount
End If
Next i ' forgot i
End Sub