VBA - 确定单元格值(String)是否与命名范围

时间:2016-05-24 03:07:38

标签: excel excel-vba range string-matching named vba

如果已经回答过这个问题已经得到了回答,我很抱歉,虽然我已经搜索过但没有运气。简而言之,我试图改变单元格颜色,如果该单元格值与命名范围内的值不匹配。

虽然没有一个方法适合我,但我尝试了很多方法,非常感谢vba大师提供的任何帮助。

基本上我在sheet1(Create)G2:G5000上有一个值列表,当他们不匹配sheet2(列表)上的值时我需要知道它们:S2:S64< - 这个命名范围是使

请查看我目前的代码副本

Sub testMake()

    Dim MkData As Range, MkVal As Range
    Dim MKArray As Variant

    Set MkData = Worksheets("Create").Range("G2:G5000")
    Set MkVal = Worksheets("Lists").Range("Make")

    For Each MyCell In MkData
        If MyCell.Value <> Range("MkVal") Then
            MyCell.Interior.ColorIndex = 6
        Else
            MyCell.Interior.ColorIndex = xlNone
        End If

    Next


End Sub

感谢大家提前提供任何帮助,我现在已经看了好几天了,似乎没有比我开始时更接近。

2 个答案:

答案 0 :(得分:1)

虽然我会使用条件格式,但您可以稍微调整代码,如下所示以编程方式执行此操作:

Sub testMake()

Dim MkData As Range
Dim MkVal As Range
Dim MKArray As Variant
Dim lngRow As Long
Dim rng1 As Range
Dim rng2 As Range


MKArray = Worksheets("Create").Range("G2:G5000").Value2
Set rng1 = Worksheets("Create").Range("G2")

Set MkVal = Range("Make")

For lngRow = 1 To UBound(MKArray)
    If IsError(Application.Match(MKArray(lngRow, 1), MkVal, 0)) Then
        If Not rng2 Is Nothing Then
            Set rng2 = Union(rng2, rng1.Offset(lngRow - 1, 0))
            Else
            Set rng2 = rng1.Offset(lngRow - 1, 0)
        End If
    End If
Next

If Not rng2 Is Nothing Then rng2.Interior.ColorIndex = 6

End Sub

答案 1 :(得分:0)

您可以使用Worksheet函数Vlookup来比较两个范围:

Sub testMake()

Dim MkData As Range, MkVal As Range
Dim MKArray As Variant
Dim result  As Variant

Set MkData = Worksheets("Create").Range("G2:G5000")
Set MkVal = Worksheets("Lists").Range("Make")

For Each MyCell In MkData
    On Error Resume Next
    result = Application.WorksheetFunction.VLookup(MyCell, MkVal, 1, False)

    If Err <> 0 Then
        result = CVErr(xlErrNA)
    End If

    If Not IsError(result) Then
        MyCell.Interior.ColorIndex = xlNone
    Else
        MyCell.Interior.ColorIndex = 6
    End If
Next

End Sub