[英]Excel VBA: Insert values from sheet 1 to sheet 2 if value in column matches
I'm a total newbie in VBA, just started this morning when confronted with a spreadsheet with ~30K rows. 我是VBA的新手,今天才刚开始,当时遇到的是包含约3万行的电子表格。
I have two worksheets: 我有两个工作表:
I want Excel to check if the number in "tohere", Cell C1 exists in any cell in "fromhere", column C, and if it does, copy the value from the corresponding row in "fromhere", column B into "tohere", Cell B1; 我希望Excel检查“ tohere”单元格C1中的单元格中是否存在“ tohere”单元格中的数字,如果存在,请将“ fromhere”列B中的相应行中的值复制到“ tohere”中,单元格B1; then do it again for C2 etc. If there's no such number in sheet "fromhere", just do nothing about this row.
然后针对C2等再次执行此操作。如果“ fromhere”工作表中没有此类数字,则无需对此行执行任何操作。
I tried this code: 我尝试了这段代码:
Dim i As Long
Dim tohere As Worksheet
Dim fromhere As Worksheet
Set tohere = ThisWorkbook.Worksheets("tohere")
Set fromhere = ThisWorkbook.Worksheets("fromhere")
For i = 1 To 100
If fromhere.Range("C" & i).Value <> tohere.Range("C" & i).Value Then
Else: fromhere.Cells(i, "B").Copy tohere.Cells(i, "B")
End If
Next i
It does what I want for the first cells that are equal (4 in my case) and then just stops without looking further. 对于第一个相等的单元格(我的情况是4个),它会执行我想要的操作,然后停下来,不进一步查找。
I tried using Cells(i, "C")
instead, same thing. 我尝试使用
Cells(i, "C")
代替,也是一样。 Using i = i + 1
after Then
doesn't help. 在“
Then
之后使用i = i + 1
并没有帮助。
I feel that the problem is in my cells addressing, but I don't understand how to fix it. 我觉得问题出在我的手机上,但我不知道如何解决。
This is how my sample "fromhere" list looks like (you can notice some numbers are missing from the C column): 这是我的示例“ fromhere”列表的样子(您会注意到C列中缺少一些数字):
This is the sample of what I get with the "tohere" list: 这是我在“ tohere”列表中得到的示例:
It gets to the point where there's no "5" in "fromhere" and stops at this point. 到达“ fromhere”中没有“ 5”的位置,并在此位置停止。
PS: i = 1 To 100
is just to test it. PS:
i = 1 To 100
仅用于测试。
This should do your job. 这应该做你的工作。 Run this and let me know.
运行这个,让我知道。
Sub test()
Dim tohere As Worksheet
Dim fromhere As Worksheet
Dim rngTohere As Range
Dim rngfromHere As Range
Dim rngCelTohere As Range
Dim rngCelfromhere As Range
'Set Workbook
Set tohere = ThisWorkbook.Worksheets("tohere")
Set fromhere = ThisWorkbook.Worksheets("fromhere")
'Set Column
Set rngTohere = tohere.Columns("C")
Set rngfromHere = fromhere.Columns("C")
'Loop through each cell in Column C
For Each rngCelTohere In rngTohere.Cells
If Trim(rngCelTohere) <> "" Then
For Each rngCelfromhere In rngfromHere.Cells
If UCase(Trim(rngCelTohere)) = UCase(Trim(rngCelfromhere)) Then
rngCelTohere.Offset(, -1) = rngCelfromhere.Offset(, -1)
Exit For
End If
Next rngCelfromhere
End If
Next rngCelTohere
Set tohere = Nothing
Set fromhere = Nothing
Set rngTohere = Nothing
Set rngfromHere = Nothing
Set rngCelTohere = Nothing
Set rngCelfromhere = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.