2012-07-20 57 views
0

我有以下問題需要解決。使用vba excel比較列與其他列

我有一個excel工作表3列和29000行。

列a是索引號。

列b是一個id號。

c欄是一個數字,它指向列的索引的

所以,如果C列200我需要去列200,並把它的B柱ID,並把它放在同一行列c索引。

這樣做的目的是爲了連接兩個項目,誰是此列C連接的ID號。

(我希望我做的意義:/)

所以我一直在嘗試VBA實現代碼。目前我使用的是嵌套的for循環,但你可以想像,運行時間已經很長了....

dim i as integer 
dim v as integer 
dim temp as integer 
i = 1 
v=1 

for i = 1 to 29000 
    if cells(i,3).value > 0 then 
    temp = cells(i,3).Value 
    cells(i,5).value = cells(1,2).value 
    for v = 1 to 29000 
     if cells(v,1).value = temp and cells(i,5).value <> cells(v,2).value then 
      cells(i,6).value = cells(v,2).value 
     end if 
     next 
    end if 
next 

所以它的工作,並執行我想要什麼,但運行時間僅僅是太長。任何想法如何簡化程序?

我很新vba和編程一般。

在此先感謝

+0

你能告訴你的結果應該是什麼樣子的快速樣品。我在理解什麼在哪裏移動有點麻煩。 – 2012-07-20 15:23:10

+0

將所有數據加載到變量數組中('arr = Range(「A1:F29000」.Value')),對該數組執行所有操作,然後將其轉儲回工作表('Range(「A1:F29000」 .Value = arr')。這會讓它更快,但是最好避免使用字典查找循環,儘可能地使用字典查找 – 2012-07-20 15:41:26

+0

因此,C列中的值 - 是您試圖在列中找到的數據A?還是行號?還有,你是否需要在VBA中做到這一點,或者是否可以接受一個公式? – SeanC 2012-07-20 16:31:10

回答

0

未經檢驗的,但編譯OK

Sub Test() 

Dim dict As Object 
Dim i As Long 
Dim temp As Long 
Dim sht As Worksheet 
Dim oldcalc 

    Set sht = ActiveSheet 
    Set dict = GetMap(sht.Range("A1:B29000")) 

    With Application 
     .ScreenUpdating = False 
     oldcalc = .Calculation 
     .Calculation = xlCalculationManual 
    End With 

    For i = 1 To 29000 
     If Cells(i, 3).Value > 0 Then 
      temp = Cells(i, 3).Value 
      Cells(i, 5).Value = Cells(1, 2).Value 
      If dict.exists(temp) Then 
       If sht.Cells(i, 5).Value <> dict(temp) Then 
        sht.Cells(i, 6).Value = dict(temp) 
       End If 
      End If 
     End If 
    Next 

    With Application 
     .ScreenUpdating = True 
     .Calculation = oldcalc 'restore previous setting 
    End With 

End Sub 

Function GetMap(rng As Range) As Object 
    Dim rv As Object, arr, r As Long, numRows As Long 
    Set rv = CreateObject("scripting.dictionary") 'EDITED to add Set 
    arr = rng.Value 
    numRows = UBound(arr, 1) 
    For r = 1 To numRows 
     If Not rv.exists(arr(r, 1)) Then 
      rv.Add arr(r, 1), arr(r, 2) 
     End If 
    Next r 
    Set GetMap = rv 
End Function