简体   繁体   中英

VBA Macro Update Cells based on a Mapping Table

I'm trying to update cells in a list based on a mapping table I have on another document. Every month, I'm going to get a list that I need to do this for. The mapping table will be constant, but the source data will change, so I'll have something like this

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

And I'll have a corresponding mapping table, I want the macro to evaluate each cell in column A against a mapping table below and update to the value in the second column of the mapping table (which is on a different sheet), is there a way to do this?

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

Basically, the final output for the data tab (first sheet) would be:

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

Thanks in advance. I've named column the ranges for column A in both sheets but I don't really know what function will allow to do this? I started to do some for each statements but got stumped.

You can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM