VBA使用countifs错误和动态范围

时间:2016-10-12 16:38:22

标签: excel vba excel-vba excel-2010 countif

我在A4中有以下一组模拟数据:B27,第4行包含标题..

4. Entity Country
5. 12   countryb
6. 13   dave
7. 14   dan
8. 15   john
9. 16   james
10. 17  josh
11. 18  george
12. 19  geni
13. 20  gina
14. 10  countrya
15. 10  countrya
16. 11  country
17. 12  countryb
18. 12  countryb
19. 13  brian
20. 14  ryan
21. 15  louis
22. 16  tom
23. 17  chris
24. 18  mad
25. 19  barb
26. 20  james
27. 10  countrya

在VBA中,我想确保没有重复的实体 - 国家/地区组合。这可以在工作表中轻松看到,公式为“= COUNTIFS($ A $ 5:$ A $ 27,A5,$ B $ 5:$ B $ 27,B5)”。如果返回的值大于1,我想突出显示实体 - 国家/地区单元格以显示重复项。在上面的例子中,第5,14,15,17,18和27行将被突出显示。

然而,在尝试创建VBA后,我被卡住了..

Sub test()

Dim cSheet As Worksheet
Set cSheet = Sheets("CL.AL1")

Dim trolSheet As Worksheet
Set trolSheet = Sheets("Control Sheet")

Dim currentRow As Integer, lastRow As Integer, currentColumn As Long
Dim listA As range, listB As range, cellA As String, cellB As String

cSheet.Select

currentColumn = 1
currentRow = 5
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
Set listA = range(Col_Letter(currentColumn) & currentRow & ":" & Col_Letter(currentColumn + 1) & lastRow)
Set listB = range(Col_Letter(currentColumn + 1) & currentRow & ":" & Col_Letter(currentColumn + 1) & lastRow)


Do While range("A" & currentRow) <> ""

cellA = (cSheet.range(Col_Letter(currentColumn) & currentRow).Value)
cellB = (cSheet.range(Col_Letter(currentColumn + 1) & currentRow).Value)

If WorksheetFunction.CountIfs(listA, cellA, listB, cellB) > 1 Then
        Union(range(Col_Letter(currentColumn) & currentRow), _
            range(Col_Letter(currentColumn + 1) & currentRow)).Select
                With Selection.Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .Color = 49407
                    .TintAndShade = 0
                    .PatternTintAndShade = 0
                End With
End If

If currentRow = lastRow Then
    currentRow = 5
    currentColumn = currentColumn + 1
    If currentColumn = 3 Then
    Exit Do
    End If
Else
currentRow = currentRow + 1
End If

Loop

Debug.Print (range(Col_Letter(currentColumn) & currentRow).Value)
Debug.Print (range(Col_Letter(currentColumn + 1) & currentRow).Value)

End Sub

Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function

执行当前VBA后,我收到运行时1004错误“无法获取工作表函数类的countifs属性”。

因此。任何人都可以帮助纠正此错误或提供替代解决方案? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

将其作为单元格A4上条件格式的公式,然后将格式复制到列的其余部分。

=COUNTIFS($A$4:$B$27,A4)>1