如何在列中搜索excel中的特定值

时间:2016-08-18 18:46:04

标签: excel excel-vba vba

我完全不知道在这种情况下该怎么做。任何帮助都会很棒。

我有三列,在第一列中我有重复条目的名称,因此我有另一列作为角色及其各自的值(PRIMARY / SECONDARY)。现在我试图在列A和B的基础上获得状态值是或否。如果列A中的名称具有作为主要的角色,则状态应为是否则否。否则表示在列A名称中是否没有任何主要值记录然后状态应为NO。以下是供参考的示例。

Name            Role        Status
C7E748588B6D    PRIMARY     Yes
C7E748588B6D    SECONDARY   Yes
C7E748588B6D    SECONDARY   Yes
C7E748588B6D    SECONDARY   Yes
C7E748588B6D    SECONDARY   Yes
5E0463D34209    SECONDARY   No
5E0463D34209    SECONDARY   No
5E0463D34209    SECONDARY   No
5E0463D34209    SECONDARY   No
46C14AEC2EB5    PRIMARY     Yes
46C14AEC2EB5    SECONDARY   Yes
46C14AEC2EB5    SECONDARY   Yes
46C14AEC2EB5    SECONDARY   Yes
46C14AEC2EB5    SECONDARY   Yes
A6C883388E3D    PRIMARY     Yes
A6C883388E3D    SECONDARY   Yes
A6C883388E3D    SECONDARY   Yes

感谢。

2 个答案:

答案 0 :(得分:0)

编辑:在下面的评论之后改变了我的答案。

这可能不是最简单的方法,但应该可行

Dim l As Long
Dim name As String
Dim cnt As Integer

l = 1
cnt = 0

For l = 1 To ActiveSheet.UsedRange.Rows.Count

    If Cells(l, 2).Value = "PRIMARY" Then
        name = Cells(l, 1)
        Do While (Cells(l + cnt, 1) = name)
            Cells(l + cnt, 3).Value = "YES"
            cnt = cnt + 1
        Loop
        cnt = 0
    ElseIf Cells(l, 3).Value = "" Then Cells(l, 3).Value = "No"
    End If

Next l

答案 1 :(得分:0)

无论数据的顺序如何,这都应该有效。它是为您提供的18行编写的。您当然必须将工作表变量和For循环的控件更新到您的特定应用程序。

Option Explicit
Sub PrimaryCheck()

Dim i As Integer
Dim w1 As Worksheet
Set w1 = ThisWorkbook.Sheets(1)
Dim SearchString As Range
Dim SearchRange As Range
Dim SearchAddress As String
Dim FoundRange As Range

Set SearchRange = w1.Range(w1.Cells(1, 1), w1.Cells(18, 1))


For i = 2 To 18
    If IsEmpty(w1.Cells(i, 3)) Then
        If w1.Cells(i, 2).Value = "PRIMARY" Then
            w1.Cells(i, 3) = "YES"
        ElseIf w1.Cells(i, 2).Value = "SECONDARY" Then
            Set SearchString = w1.Cells(i, 1)
            SearchAddress = w1.Cells(i, 1).Address
            Set FoundRange = SearchRange.Find(SearchString, w1.Cells(i, 1), , , , xlNext, True)
            Do While Not FoundRange Is Nothing And FoundRange.Address <> SearchAddress

                If w1.Cells(FoundRange.Row, 2).Value = "PRIMARY" Then
                    w1.Cells(i, 3) = "YES"
                End If
                Set FoundRange = SearchRange.FindNext(FoundRange)
            Loop
            If IsEmpty(w1.Cells(i, 3)) Then
                w1.Cells(i, 3).Value = "NO"
            End If
        End If
    End If
Next i
End Sub