我有2张Excel表格。 我想将“CategoryIds”列中的值复制到另一个工作表 在该表的SKU字段上有匹配列。
我需要此表中的“CategoryIds”列:NewDepotProdsDB.xls,
将被复制到此工作表中:DEPOT_products.xlsx,
基于与“SKU”列的匹配。
NewDepotProdsDB.xls :
SKU CategoryIds
5845 8
8545 58
...
DEPOT_products.xlsx :
SKU CategoryIds
5845 > need to copy the value from NewDepotProdsDB.xls here >
8545 > need to copy the value from NewDepotProdsDB.xls here >
....
这可能吗?
我可以暂时复制这两列(SKU CategoryIds) 到DEPOT_products.xlsx工作表,然后使用公式或其他东西。 我不擅长Excel,也不知道我在做什么。
注意:我有97-2003版本的Excel。
由于
答案 0 :(得分:1)
试试这段代码。您应该将此宏添加到文件DEPOT_products.xlsx。我想你的数据在A和B列的每个文件的Sheet1中(从第二行开始),但是如果你不对,你可以轻松地改变它:
Sub test()
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim lastrow1 As Long
Dim lastrow2 As Long
Dim vlookup As String
On Error GoTo ErrHandler
'current workbook (DEPOT_products.xlsx)'
Set Wb1 = ThisWorkbook
'path to the NewDepotProdsDB.xls file'
Workbooks.Open Filename:="C:\NewDepotProdsDB.xls", ReadOnly:=True
Set Wb2 = ActiveWorkbook
'set correct name of the sheet with your data in file DEPOT_products.xlsx'
Set sh1 = Wb1.Sheets("Sheet1")
'set correct name of the sheet with your data in file NewDepotProdsDB.xls'
Set sh2 = Wb2.Sheets("Sheet1")
'determining last row of your data in file DEPOT_products.xlsx'
lastrow1 = sh1.Range("A" & sh1.Rows.Count).End(xlUp).Row
'determining last row of your data in file NewDepotProdsDB.xls'
lastrow2 = sh2.Range("A" & sh2.Rows.Count).End(xlUp).Row
'write the formula to match your SKU column in DEPOT_products.xlsx to SKU column in NewDepotProdsDB.xls and get column CategoryIds'
vlookup = "VLOOKUP(A2," & "[" & Wb2.Name & "]" _
& sh2.Name & "!" & "$A$2:$B$" & lastrow2 _
& ",2, 0)"
sh1.Range("B2:B" & lastrow1).Formula = "=IF(ISERROR(" & vlookup & ")," _
& """not found""" & "," & vlookup & ")"
'copy formulas result and paste them like a values (to kill formulas) - you can comment the code below, so you will have formulas instead values'
sh1.Range("B2:B" & lastrow1).Copy
sh1.Range("B2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
' close NewDepotProdsDB.xls
Wb2.Close False
ErrHandler:
If Err.Number = 1004 Then
MsgBox "File not found: " + Err.Description
Else
MsgBox "Unknown error: " + Err.Description
End If
End Sub
希望它有所帮助。我试图详细评论代码,但如果你有一些问题,请问。
<强> UPD:强> 或者,您可以使用公式代替VBA代码。只需在包含数据的工作表中的DEPOT_products.xlsx中写入它(列CategoryIds):
=IF(ISERROR(VLOOKUP(A2,'C:\Work\[NewDepotProdsDB.xls]Sheet1'!$A$2:$B$500,2,0)),"not found",VLOOKUP(A2,'C:\Work\[NewDepotProdsDB.xls]Sheet1'!$A$2:$B$500,2,0))
1)将A2
更改为DEPOT_products.xlsx中第一个SKU的地址,并将此公式放入单元格,对应第一个CategoryIds
2)将'C:\Work\[NewDepotProdsDB.xls]Sheet1'!$A$2:$B$500
更改为NewDepotProdsDB.xls文件的路径+正确的工作表+正确的SKU和CategoryIds范围。
3)将此公式放到SKU的最后一行
答案 1 :(得分:0)
您可以简单地使用vlookup公式。
示例:
如果SKU值在B col中,从depot_product xlsx的第5行开始,类别ids和sku值在NewDepotProdsDB(在C14到D15)单元格的sheet2中,则可以使用以下公式。
= VLOOKUP(B5,[NewDepotProdsDB.xls] Sheet 2中$ C $ 14:!$ d $ 15,2,0)
数字2告诉excel从sku id列获取第二列的值。