Excel VBA连接唯一值查找

时间:2016-07-12 16:18:57

标签: excel vba macros

早上好!我正在尝试创建一个VBA功能,并感谢您提供的任何帮助,以使我走上正确的轨道。简而言之,对于工作表检查的A列中的每个值,我需要连接工作表结果中列B中的所有唯一值,其中工作表检查的列A =工作表结果的列A.我正在努力从哪里开始,似乎找不到任何好的指导。提前谢谢你的帮助。非常感谢。

从这开始,让我的方向在连续...我知道& ExamID部分是错误的,但我不确定我需要哪些代码与RX721502的下一个实例连接:

Dim ExamID As Range
Dim strConcat As String
Dim i As Integer
i = 2

Do While Cells(i, 1).Value <> ""
    For Each ExamID In Range("A2:A10000")
        If InStr(ExamID.Value, "RX721502") > 0 Then
        Cells(i, 18).Value = ActiveCell.Offset(0, 10) & ", " & ExamID
        End If
    Next ExamID
    Cells(2, 18) = Trim(Cells(2, 18))
i = i + 1
Loop

1 个答案:

答案 0 :(得分:0)

尝试以下代码,它将Concatenate城市字符串放入工作表 SourceExams ,第2列。

Sub use_VLookup()


Dim conOG                               As String
Dim SourceExams                         As Worksheet
Dim SourceFindings                      As Worksheet
Dim lastrow, lastrow2                   As Long
Dim rowfound                            As Long
Dim Vlookup_result                      As Variant

Set SourceExams = ActiveWorkbook.Sheets("Source-Exams")
Set SourceFindings = ActiveWorkbook.Sheets("Source-Findings")

lastrow = SourceExams.UsedRange.Rows.count
lastrow2 = SourceFindings.UsedRange.Rows.count

For i = 2 To lastrow
    j = 2
    While j <= lastrow2
        ' search Worksheet Cities workcheet for match on Column A, and return the value in column B
        Vlookup_result = Application.VLookup(SourceExams.Cells(i, 1), SourceFindings.Range(SourceFindings.Cells(j, 1), SourceFindings.Cells(lastrow2, 2)), 2, False)
        If IsError(Vlookup_result) Then
            ' do nothing , you can add erro handling, but I don't think it's necesary
        Else
            conOG = conOG & ", " & Application.WorksheetFunction.VLookup(SourceExams.Cells(i, 1), SourceFindings.Range(SourceFindings.Cells(j, 1), SourceFindings.Cells(lastrow2, 2)), 2, False)
            rowfound = Application.WorksheetFunction.Match(SourceExams.Cells(i, 1), SourceFindings.Range(SourceFindings.Cells(j, 1), SourceFindings.Cells(lastrow2, 1)), 0)
        End If

        j = j + rowfound
        ' if first found go to row 3
        If j <= 2 Then j = 3
    Wend
    SourceExams.Cells(i, 2) = conOG
    conOG = ""
Next i

End Sub