Excel:使用工作表中的值作为索引在不同的工作表中列出,并替换第一个工作表中的值

时间:2013-01-05 03:34:07

标签: excel vba excel-vba

我有一个XL文件,其中包含一些要操作的数据。我想我需要使用VB脚本来做到这一点 - 但也许有一个更简单的方法与公式。同样,有人能指出实现以下目标的两种方式吗?

我在Sheet 1中有一列数值(ID)。 我想使用每个ID作为索引来查找工作表2中的列表。 表2有两列 第一列是索引,第二列是文本字符串 例如

1 Apple

2 Orange

3梨

我想要的是用工作表2中的查找文本字符串替换工作表1中的ID列!

多数人...... 请帮忙!

1 个答案:

答案 0 :(得分:2)

那里并非艰难。以下是一些解决方案......

使用VBA:

我知道你说你对VB有点新意,所以我试着解释每一行。此外,代码是空手而归,如果我在某处留下错误,请原谅我。

Sub replaceData()

dim i as integer, j as integer 'These are just some variables we'll use later.
dim sheetOne as worksheet, sheetTwo as worksheet, myWb as workbook
dim myData as string, myId as string

set myWB = excel.activeworkbook 'These three lines set your workbook/sheet variables.
set sheetOne = myWB.worksheets("Old Data")
set sheetTwo = myWB.worksheets("New Data")

for i = 1 to sheetTwo.usedrange.rows.count 'This loops through the rows on your second sheet.
   myId = sheetTwo.cells(i,1).value 'This assigns the value for your id and the data on your second sheet.
   myData = sheetTwo.cells(i,2).value
   for j = 1 to sheetOne.usedrange.rows.count 'This loops through the rows on your first sheet.
      if sheetOne.cells(j,1).value = myId then 'This checks each row for a matching id value.
         sheetOne.cells(j,1).value = myData 'This replaces that id with the data we got from the second sheet.
      end if
   next j
next i

end sub

使用Excel公式:

  1. 将以下公式放在第一个工作表的单元格C1中( 包含您要替换的ID的工作表)。 **注意你会的 必须用名称替换“InsertSheetTwoNameHere”部分 你的第二张表(不要删除那些单引号)。也 请注意,您需要将“1000”替换为最后一个的数字 在第二张中使用了行。

    = VLOOKUP(A1,” InsertSheetTwoNameHere” $ A $ 1:$ B $ 1000,2,FALSE)

  2. 接下来,只需拖动使其自行复制的单元格上的手柄即可 (无论它被称为什么)一直到你的结束 范围。

  3. 接下来,复制这些单元格,然后使用。将它们粘贴到ID上 仅限值设置。

  4. 希望这会有所帮助,祝你好运。