Vba 如果相同值,则从不同图纸复制车道
我在表1中有5列,在表2中也有5列。产品的名称在A中。但有时产品的特征(在B、C、D、E中)在表2中会发生变化。我希望它实现表1中的特征 我试过Vlookup,但它只在一个细胞内起作用Vba 如果相同值,则从不同图纸复制车道,vba,excel,Vba,Excel,我在表1中有5列,在表2中也有5列。产品的名称在A中。但有时产品的特征(在B、C、D、E中)在表2中会发生变化。我希望它实现表1中的特征 我试过Vlookup,但它只在一个细胞内起作用 Sub test() With Sheets("Feuil1") .Range("B1").Value = WorksheetFunction.VLookup(.Range("A1").Value, Sheets("Feuil2").Range("A1:B100"), 2, False) End With
Sub test()
With Sheets("Feuil1")
.Range("B1").Value = WorksheetFunction.VLookup(.Range("A1").Value, Sheets("Feuil2").Range("A1:B100"), 2, False)
End With
End Sub
此外,我无法复制所有行,因为F列不应更改…而A列中sheet1中的产品不整洁,并且有一些重复…您需要一个循环来更新每一行,并且还需要更新每一列 我建议改为使用,这样每行只需匹配一次即可获得行号,然后就可以复制该行的所需值
Option Explicit
Public Sub UpdateData()
Dim WsDest As Worksheet 'destination workbook to write in
Set WsDest = ThisWorkbook.Worksheets("Feuil1")
Dim WsSrc As Worksheet 'source workbook to match with
Set WsSrc = ThisWorkbook.Worksheets("Feuil2")
Dim LastRow As Long 'last used row in workbook
LastRow = WsDest.Cells(WsDest.Rows.Count, "A").End(xlUp).Row
Dim iRow As Long, MatchedRow As Long
For iRow = 1 To LastRow 'loop through all rows from row 1 to last used row and update each row
MatchedRow = 0 'initialize
On Error Resume Next 'if no match found then ignore error
MatchedRow = WorksheetFunction.Match(WsDest.Cells(iRow, "A"), WsSrc.Columns("A"), 0) 'get the row number of the match
On Error GoTo 0 'reactivate error reporting
'if it didn't match then MatchedRow is still 0
If MatchedRow > 0 Then 'if a match was found then copy values
WsDest.Cells(iRow, "B").Value = WsSrc.Cells(MatchedRow, "B").Value
WsDest.Cells(iRow, "C").Value = WsSrc.Cells(MatchedRow, "C").Value
WsDest.Cells(iRow, "D").Value = WsSrc.Cells(MatchedRow, "D").Value
WsDest.Cells(iRow, "E").Value = WsSrc.Cells(MatchedRow, "E").Value
Else
'didn't find a match
'you can remove the Else part if you want to do nothing here
End If
Next iRow
End Sub
如果要复制的列是连续的,如B、C、D、E,则可以在一个复制操作中进行复制,这比4个复制操作(每列1个)要快:
可能是
VLookup
不起作用,因为您在Feuil2
中的范围没有按字母顺序列出。我的VLookup起作用,但只有一个单元格,或者我希望它复制B、C、D、E。。。。但不是最后一个细胞。在每一行。正是我想做的!它甚至可以在Mac上运行。我不知道比赛的事,泰。
WsDest.Range("B" & iRow & ":E" & iRow).Value = WsSrc.Range("B" & MatchedRow & ":E" & MatchedRow).Value