基于映射表的VBA宏更新单元

时间:2016-02-29 19:48:56

标签: excel vba macros

我正在尝试根据我在另一个文档上的映射表更新列表中的单元格。每个月,我都会得到一份我需要这样做的清单。映射表将是常量,但源数据将会改变,所以我会有类似的东西

Column A  Column B
Name      Description
Test1     Test for SO
Test2     Test2 for SO
...
Test100   Test100 for SO

我将有一个相应的映射表,我希望宏根据下面的映射表评估A列中的每个单元格,并更新到映射表的第二列中的值(位于不同的工作表上) , 有没有办法做到这一点?

Column A    Column B 
Name        Real Name
Test1       Fund1
Test2       Fund2
...
Test100     Fund100

基本上,数据选项卡(第一张)的最终输出将是:

Column A    Column B
Name        Description
Fund1       Test for SO
Fund2       Test2 for SO
...
Fund100     Test100 for SO

提前致谢。我已在两个工作表中为列A的范围命名列,但我真的不知道允许执行此操作的功能是什么?我开始为每个陈述做一些事情,但很难过。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

Option Explicit

Sub map()

Dim SourceData As Worksheet: Set SourceData = ThisWorkbook.Sheets("Sheet1") 'Change the name of the sheet
Dim Mapping As Worksheet: Set Mapping = ThisWorkbook.Sheets("Sheet2") 'Change the name of the sheet

Dim SourceDataLstr As Long, MappingLstr As Long
Dim i As Long, j As Long
Dim RawDataKey As String, MappingKey As String

SourceDataLstr = SourceData.Range("A" & Rows.Count).End(xlUp).Row 'Find the lastrow in the Source Data Sheet
MappingLstr = Mapping.Range("A" & Rows.Count).End(xlUp).Row 'Find the lastrow in the Mapping Sheet

With SourceData

For i = 2 To SourceDataLstr

RawDataKey = .Cells(i, "A").Value

        For j = 2 To MappingLstr

                MappingKey = Mapping.Cells(j, "A").Value

                If MappingKey = RawDataKey Then
                    .Cells(i, "A").Value = Mapping.Cells(j, "B").Value
                    Exit For
                End If

        Next j

Next i

End With

End Sub