2014-10-18 100 views
1

我是VBA的总新手,今天早上刚开始面对一个大约30K行的电子表格时。Excel VBA:如果列中的值匹配,将值从表1插入表2

我有两个工作表:

  1. 名为“tohere”,包含在列序数C.
  2. 名为“fromhere”,包含B列C列数和值它基本上是相同的序数,但有些错过了 - 这就是为什么我开始写第一个宏的原因。

我希望Excel检查“tohere”中的数字C1是否存在于“fromhere”列中的任何单元格中,如果存在,请从“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")代替,同样的事情。在Then后使用i = i + 1没有帮助。

我觉得问题出在我的单元格中,但我不明白如何解决它。

这是我的样品“fromhere”名单的样子(你可以看到一些数字是从C柱丢失):

fromhere

这是我所用“tohere得到样品“的文章:

tohere

它到达那里没有一点‘’中‘fromhere’5。在这一点上停止。

P.S .: i = 1 To 100只是为了测试它。

+0

根据你的代码,两张纸的col C中的序数必须在同一行。你可以在一些图像共享网站或保存箱中上传你的床单的屏幕截图,并在这里发布链接。 – ZAT 2014-10-18 14:08:27

回答

1

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

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 
+1

Jur,它适合我的测试列表!我会尝试为我的真实工作(即〜30 K行的工作簿)运行,并让它知道它是否有效。非常感谢! – 2014-10-18 14:24:10

+0

当然!它应该也适用于你的真实工作。 – 2014-10-18 14:32:27

+1

嗯,我让它工作了15分钟,它处理了8000行,一切都按照它应该的方式工作。谢谢,你救了我的一天,现在我会提供我的工作,并坐下来了解你的代码:) – 2014-10-18 14:48:40