如何比较excel中的行并执行if语句

我有一个电子表格,我需要计算一个特定区域已经完成的次数,我知道当某个标准存在时,另一个电子表格中的字段应该增加。

for i to rows.length if Cell(A,i) == Cell(A,i+1) AND Cell(D,i) != Cell(D,i+1) otherspreadsheet.field++ else if Cell(A,i) != Cell(A,i+1) otherspreadsheet.field++ 

我不知道如何使用Microsoft Excel的VBA,任何帮助将不胜感激。

+++

我正在玩你提供给我熟悉的代码,并最终找出这个问题。 strYear似乎不工作, strYear = InputBox("enter year") 。 如果我进入2014年,计数出来为0.但是,如果我从下面的代码"strYear" to 2014replace"strYear" to 2014那么它的工作。

 With MySheet For i = 4 To LastRow If .Cells(i, "AA").Value = "strYear" Then GreensFCounter = GreensFCounter + 1 Else GreensFCounter = GreensFCounter End If Next i End With MsgBox (GreensFCounter) 

下面的代码没有经过testing,但是有很多评论 – 我认为它会在每个部分都会回答你的问题。

一个快速的笔记虽然:你正在比较一个单元格下面的单元格,对不对? 在表面上看起来不错,但是你需要考虑的一个angular落案例是范围的结束:你会比较一个空单元格。

 Option Explicit Sub CheckCellsAndTrackResults() Dim i As Long, LastRow As Long Dim Counter1 As Long, Counter2 As Long Dim MySheet As Worksheet 'initialize our counter variables Counter1 = 0 Counter2 = 0 'lets assume the comparison is happening on Sheet1 Set MySheet = ThisWorkbook.Worksheets("Sheet1") 'identify the last row for our loop LastRow = MySheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'NOTES: 'use a single equal sign ("=") for equivalent 'use less/greater ("<>") for not equivalent 'lets loop through rows 1 to the last row using a 'cool little VBA construct, a With...End With qualifier, 'to make some of our cell-checking easier to write: With MySheet For i = 1 To LastRow If .Cells(1, i).Value = .Cells(1, i + 1).Value And _ .Cells(4, i).Value <> .Cells(4, i + 1).Value Then Counter1 = Counter1 + 1 ElseIf .Cells(1, i).Value <> .Cells(1, i + 1) Then Counter2 = Counter2 + 1 Else 'maybe do something else here? End Next i End With 'finally, we can write out the counter results somewhere 'like this: 'MySheet.Cells(x, y) = Counter1 'MySheet.Cells(p, q) = Counter2 End Sub