excel:修改“的值”;工作表1“;使用“中的值”;工作表2“;名字相同的地方
我们有两张工作表excel:修改“的值”;工作表1“;使用“中的值”;工作表2“;名字相同的地方,excel,vba,Excel,Vba,我们有两张工作表 源工作表是“profes” 目标工作表为“primaria” 两个工作表共有的数据是“名称”列。 ie:David Smith Weston出现在两张工作表中。 我们需要“查找”每个学生的名字,并将值从“profes”粘贴到“primaria”。我已经有了大部分代码,但我不知道如何添加“查找”部分。正如你所看到的,这是错误的 Sub Button1_Click() Set Source = ActiveWorkbook.Worksheets("profes") Set Tar
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
在比较两个工作表之间的两个范围时,您有一个
用于
循环,并用匹配
功能替换第二个循环
当您循环“profes”表的范围,并检查每个单元格的值是否在“primaria”表的第二个范围内时,我使用了lookupring
,正如您在下面的代码中所看到的,您需要根据需要调整范围
代码
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
使用工作表的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
您没有使用查找(VLOOKUP)有什么原因吗?
j=j+1
。这一定是在你的IF语句中。你总是想增加J的值,所以它会检查所有单元格。无论如何,考虑使用PivotTables来恢复教师和学生/学生的数据<代码> N5:R1000 < /代码>不是100行。它是996行乘5列,总共4980个单元格。这几乎可以完美地工作。我想我做错了什么。我有一大块行,其中is不添加值,但每个工作表中都存在名称。就好像它是在“跳转”块,然后重新开始。@user3149225是完全匹配还是接近匹配?它们完全匹配。也许如果我们去掉可能有用的空格。我将如何实现这一点?我的意思是我想它是TRIM,但我不知道放在哪里。@user3149225如果空格在Source
中,你可以使用TRIM(C.Value)