计算差异量并返回列名与计数

时间:2015-06-16 09:57:58

标签: excel vba excel-vba

我发现2个工作表之间存在差异,代码如下:

For Each mycell In ActiveWorkbook.Worksheets(shtSheet2).UsedRange 
If Not mycell.Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(mycell.Row, mycell.Column).Value Then
    mycell.Interior.Color = vbYellow
    difference = difference + 1
End If

If mycell.Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(mycell.Row, mycell.Column).Value Then
   matches = matches + 1
End If

当单元格中的值不匹配时,它突出显示该单元格黄色并递增计数,以便我知道差异的总量。

我有标题部门,名称,销售,日期开始,日期结束。如何返回列的差异量?

e.g。

Differences 
department : 3 
sales : 0
Date Start : 1
Date end : 2

1 个答案:

答案 0 :(得分:0)

difference作为Array,并增加与当前Column对应的组件。 如果需要,您可以使用matches执行类似操作。另外,您可以缩短两个If

Dim difference(1 To 5) As Long
Dim matches(1 To 5) As Long
For Each mycell In ActiveWorkbook.Worksheets(shtSheet2).UsedRange
Dim col as Long
col = mycell.Column
If Not mycell.Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(mycell.Row, mycell.Column).Value Then
    mycell.Interior.Color = vbYellow
    difference(col) = difference(col) + 1
Else
    matches(col) = matches(col) + 1
End If

您可以查看Chip Pearson's guide