我是VBA的新手,今天早上刚开始遇到一个行距约为30K的电子表格。
我有两个工作表:
我希望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列中缺少一些数字):
这是我从“tohere”列表中得到的样本:
它已经到了“从哪里”没有“5”并且在此时停止。
P.S。:i = 1 To 100
只是为了测试它。
答案 0 :(得分:2)
这应该可以胜任你的工作。运行此并告诉我。
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