excel:使用“worksheet2”中的值修改“worksheet1”的值,其中name是相同的

时间:2018-03-26 10:57:41

标签: excel-vba vba excel

我们有两个工作表。

  1. 源工作表是“profes”
  2. 目标工作表是“primaria”
  3. 两个工作表共有的数据是名称列。 即:David Smith Weston出现在两个工作表中。 我们需要“查找”每个学生的姓名并将值从“profes”粘贴到“primaria”。我已经将大部分代码工作了但是我不知道如何添加“查找”部分。你可以看出它是错的。

    Actions action = new Actions(driver);
    action.MoveByOffset(500, 500).ContextClick().Perform();
    

2 个答案:

答案 0 :(得分:2)

比较2个工作表中的2个范围时,您有1个For循环,并用Match函数替换第二个循环。

一旦你遍历“profes”工作表的范围和每个单元格,你检查是否在“primaria”工作表的第二个范围内找到了该值,我使用了LookupRng,如下面的代码所示 - 您需要根据需要调整范围。

代码

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

答案 1 :(得分:0)

使用工作表的MATCH函数从目标列A中的源列C中找到名称。

您提供的代码难以破译,但这可能更接近您想要完成的任务。

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