简体   繁体   中英

Excel Macro (VBA) that checks cell values against a list in another workbook

I have two workbooks, one that is data (We'll call WB 1) that needs the values in column k checked against values on another workbook (We'll call WB 2) that contains the true values for the entries. Each entry has a quantity attached to it so the price varies dependent on that. WB 1 is in a list with entries on each row and WB 2 has an item on each row and each column is the price for that quantity. I need a macro that will check these values against each other and replace any values on WB 1 with the correct value from WB 2.

Example Data:

WB 1
    | Column A  | Column C | Column K |
     ---------------------------------
    | Item Name |    30    |  $5.42   |

WB 2
    | Column A  | Column F | Column G | Column H | ... |
                     15         30         45
     --------------------------------------------------
    | Item Name |  $2.86   |   $4.53  |  $6.00   | ... |

you can use vlookup to perform a search and follow the instruction below for better performance.

  1. set the WB1 as source and WB2 as destination work.

  2. select the item in WB1 with a "For loop". Make sure you select the appropriate column and its tuple

    For rowIndex = 2 To lastRow

(Alternatively use a range)

  1. Perform a vlookup between the search.

  2. paste/display the output in required column

  3. Increment the loop (Next Row index).

(let me know if you need exact code snippets)

Regards, Mani

Here is the code snippet

*points to remember

Phase 1: Loading the workbook

  1. You would need to first refer the source workbook by path or call it as loading the workbook.
  2. Then assign the source workbook say(set sourceworkbook = "workbook derived from the path and assigned to a variable"
  3. Many code is available in stackoverflow to achieve the same.

Phase 2: Calculation/Manipulation/Logic

lastRow = SourceData.Rows.Count

For rowIndex= 2 to lastRow
  lTemp = sourceWorksheet.Cells(rowIndex, "Q").Value
  lDigit = VLOOKUP( value, table, index_number, [not_exact_match] )  'not_exact_match is usually false
  DestinationWorksheet.Cells(rowIndex, "AM").Value = lDigit
next rowIndex

[Remember to declare the variables with appropriate datatypes matching your requirement]/

Regards, Mani

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