Excel VBA:如果列中的值匹配,则将值从表格1插入到表格2

我是VBA的新手,今天早上刚刚开始面对一个大约30K行的电子表格。

我有两个工作表:

  1. 命名为“tohere”,包含C列中的序数
  2. 命名为“fromhere”,包含C列中的数字和B列中的值。它们基本上是相同的序数,但有些却不见了 – 这就是为什么我开始写一个macros的原因。

我希望Excel检查“tohere”中的数字C1是否存在于“fromhere”列C中的任何单元格中,如果是,则将“fromhere”列B中相应行的值复制到“tohere” ,Cell B1; 然后再做C2等。如果“fromhere”表中没有这样的数字,那么对这一行不做任何事情。

我试过这个代码:

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 

它做我想要的第一个单元格是相同的(在我的情况下是4),然后停下来不看。

我尝试使用Cells(i, "C")而不是,同样的事情。 以后使用i = i + 1 Then没有帮助。

我觉得问题出在我的细胞中,但我不明白如何解决这个问题。

这就是我的示例“fromhere”列表的样子(您可以注意到C列中缺less一些数字):

从这里

这是“tohere”列表中的示例:

到这里

到了从这里开始没有“5”的地步到此为止。

PS: i = 1 To 100只是为了testing它。

这应该做你的工作。 运行这个,让我知道。

 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