当具有相同的识别单元时,如何用相同的单元替换多个数据单元?

时间:2014-06-06 06:13:07

标签: excel vba excel-vba excel-formula excel-2007

所以我对VBA很新,所以我为我可怕的编码道歉。我一直在寻找几个小时来找到这个看似简单的问题的答案,我可能已经遇到过它,但只是不明白它是什么。

基本上我要做的是使用识别变量来对一组变量进行分类。我看到的数据看起来就像专辑中的顶级图像,我需要的东西看起来就像专辑中的第二张图片(除了我有超过20,000点)。如果有人能帮助我,我将非常感激。

enter image description here

enter image description here

到目前为止,我有:

Sub Try_3()
SessionID_Cell = Value.Range("D3:D10047")
SessionID_Change = Value.Range("I2:I5748")
Name_Change = Value.Range("J2:J5748")

For Each SessionID_Cell In Range("D2:D10047")

If SessionID_Cell = SessionID_Change Then
SessionID_Cell.Value = Replace(SessionID_Cell, SessionID_Change, Name_Change)
Else
End If

Next SessionID_Cell


End Sub

2 个答案:

答案 0 :(得分:2)

试试这个:

Sub test()
    Dim idcs As Range, idc As Range
    Dim rng As Range, idns As Variant
    Dim i As Long

    With Sheet1 '~~> Sheet where your data reside, change to suit
        Set idcs = .Range("C2", .Range("C" & .Rows.Count).End(xlUp))
        Set rng = .Range("B2", .Range("B" & .Rows.Count).End(xlUp))
        '~~> pass name id's to array
        idns = Application.Transpose(rng)
    End With

    With CreateObject("Scripting.Dictionary")
        '~~> Dump id's and equivalent city on Dictionary
        For Each idc In idcs
            If Not .Exists(idc.value) Then
                .Add idc.Value, idc.Offset(0, 1).Value
            End If
        Next
        '~~> replace all name id's with equivalent city
        '~~> using the info dumped in the Dictionary
        For i = LBound(idns) To UBound(idns)
            If .Exists(idns(i)) Then idns(i) = .Item(idns(i))
        Next
        '~~> Change this part if you want to dump new data in another sheet
        rng = Application.Transpose(idns)
    End With
End Sub

这将用实际城市替换所有名称标识符 这就像在C和D设置的条件下一次查找和替换 如果标识符没有匹配的城市,它将保持原样 这是你正在尝试的吗?

答案 1 :(得分:1)

我觉得宏对于这个有点过分了....为什么不使用简单的VLOOKUP?

=VLOOKUP(B2,$C$2:$D$4,2,FALSE)

以下示例中的参数含义

B2是要搜索的值

$C$2:$D$4是要查看的表的范围

2是返回值

的上述范围的列索引

FALSE - 完全匹配

enter image description here