2014-10-18 99 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