[英]excel: Modify the values of “worksheet1” using values from “worksheet2” where name is the same
We have two worksheets. 我们有两个工作表。
The data common to both worksheets is the name column. 这两个工作表的通用数据是名称列。 ie: David Smith Weston appears in both worksheets.
即:David Smith Weston出现在两个工作表中。 We need to "lookup" each students name and paste values from "profes" to "primaria".
我们需要“查找”每个学生的姓名,并将值从“专业”粘贴到“ primaria”。 I have most of the code working already BUT I don't know how to add the "lookup" part.
我的大多数代码都已经工作了,但我不知道如何添加“查找”部分。 As you can see it's wrong.
如您所见,这是错误的。
Sub Button1_Click()
Set Source = ActiveWorkbook.Worksheets("profes")
Set Target = ActiveWorkbook.Worksheets("primaria")
j = 1 ' Start copying to row 1 in target sheet
For Each c In Source.Range("N5:R1000") ' Do 100 rows
**If Source.Cells(j, "C").Value = Target.Cells(j, "A").Value** Then
Target.Cells(j, "N").Value = Source.Cells(j, "D").Value
j = j + 1
End If
Next c
End Sub
When comparing 2 ranges between 2 worksheets, you have 1 For
loop, and replace the second loop with the Match
function. 比较2个工作表之间的2个范围时,您有1个
For
循环,然后用Match
函数替换第二个循环。
Once you loop over your "profes" sheet's range, and per cell you check if that value is found within the second range in "primaria" sheet, I used LookupRng
, as you can see in the code below - you will need to adjust the range cording to your needs. 一旦您遍历“ profes”表的范围,并检查每个单元格的值是否在“ primaria”表的第二个范围内,就使用
LookupRng
,如下面的代码所示-您将需要调整范围满足您的需求。
Code 码
Option Explicit
Sub Button1_Click()
Dim Source As Worksheet, Target As Worksheet
Dim MatchRow As Variant
Dim j As Long
Dim C As Range, LookupRng As Range
Set Source = ActiveWorkbook.Worksheets("profes")
Set Target = ActiveWorkbook.Worksheets("primaria")
' set up the Lookup range in "primaria" sheet , this is just an example, modify according to your needs
Set LookupRng = Target.Range("A2:A100")
For Each C In Source.Range("N5:R1000") ' Do 100 rows
If Not IsError(Application.Match(C.Value, LookupRng, 0)) Then ' Match was successfull
MatchRow = Application.Match(C.Value, LookupRng, 0) ' get the row number from "primaria" sheet where match was found
Target.Cells(C.Row, "N").Value = Source.Cells(MatchRow, "D").Value
End If
Next C
End Sub
Use the worksheet's MATCH function to locate names from the source column C in the target's column A. 使用工作表的MATCH函数在目标列A中找到源列C中的名称。
Your supplied code is hard to decipher but perhaps this is closer to what you want to accomplish. 您提供的代码很难破译,但也许这更接近您想要完成的工作。
Sub Button1_Click()
dim j as long, r as variant
dim source as worksheet, target as worksheet
Set Source = ActiveWorkbook.Worksheets("profes")
Set Target = ActiveWorkbook.Worksheets("primaria")
with source
for j = 5 to .cells(.rows.count, "C").end(xlup).row
r=application.match(.cells(j, "C").value2, target.columns("A"), 0)
if not iserror(r) then
target(r, "D").resize(1, 5) = .cells(j, "N").resize(1, 5).value
end if
next j
end with
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.