我想在Excel工作表中有条件地计算行数。我编写了计算整个范围内数字的代码。但是我需要为不同的列分隔结果。例如,现在我查看范围C2:N59,但我希望看到每个条件的列D,E和G,H等的结果。我应该为它写一个循环?
这是我的代码:
Function RabigatorCount()
Dim zelle As Range
Dim i As Integer
Dim Rabigator() As Integer
Dim posMonitoring As Integer
Dim j As Integer
Dim intCounter(9) As Integer
Set zelle = Cells.Find("is_monitoring_relevant")
posMonitoring = zelle.Column
For j = 3 To 16 Step 3
For i = 2 To 59
If Cells(i, posMonitoring).Value = "c" And Cells(i, j + 1).Value < 0 And Cells(i, j + 2).Value < 0 Then
intCounter(1) = intCounter(1) + 1
ElseIf Cells(i, posMonitoring).Value = "c" And Cells(i, j + 1).Value = 0 And Cells(i, j + 2).Value < 0 Then
intCounter(2) = intCounter(2) + 1
End If
Next i
Next j
RabigatorCount = intCounter
End Function
非常感谢:)
答案 0 :(得分:0)
如果您的问题简化为以下内容:
我查看C2:N59的范围,但是我希望看到每个条件的列D,E和G,H等的结果。我应该为它写一个循环?
然后这是一个可能的答案:
Public Sub TestMe()
Dim inspectedRange As Range
Set inspectedRange = Worksheets(1).Range("C2:N59")
Dim cnt As Long
For cnt = 1 To inspectedRange.Columns.Count Step 2
Debug.Print inspectedRange.Columns(cnt).Address
Debug.Print inspectedRange.Columns(cnt + 1).Address
Debug.Print "-------------"
Next cnt
End Sub
它打印每2列,从C
和D
开始,如下所示:
$C$2:$C$59
$D$2:$D$59
-------------
$E$2:$E$59
$F$2:$F$59
-------------
$G$2:$G$59
$H$2:$H$59
-------------
它允许您按照您希望的方式进一步处理这些范围 - inspectedRange.Columns(cnt)
和inspectedRange.Columns(cnt+1)
。如果你想在嵌套循环中使用j
和i
,这是获取单元格并对它们执行某些操作的可能方法:
Public Sub TestMe()
Dim inspectedRange As Range
Set inspectedRange = Worksheets(1).Range("C2:N59")
Dim j As Long, i As Long, cnt As Long
Dim col1 As Range
Dim col2 As Range
For cnt = 1 To inspectedRange.Columns.Count Step 2
Set col1 = inspectedRange.Columns(cnt)
Set col2 = inspectedRange.Columns(cnt + 1)
For j = 3 To 16 Step 3
For i = 2 To 59 Step 1
With Worksheets(1)
Debug.Print .Cells(j, col1.Column).Address
Debug.Print .Cells(i, col2.Column).Address
End With
Next i
Next j
Next cnt
End Sub