2015-09-01 123 views
1

一些google搜索後,我用下面的:在Excel VBA中,如何比較兩個範圍並將一個範圍的偏移量複製到另一個範圍的偏移量中?

Sub Find_Matches() 
    Dim CompareRange As Variant, ToCompare As Variant, x As Variant, y As Variant 
    Set CompareRange = Worksheets("names").Range("A1:A500") 
    Set ToCompare = Worksheets("Main").Range("C1:C500") 
    For Each x In ToCompare 
     For Each y In CompareRange 
      If x = y Then x.Offset(0, 2) = y.Offset(0, 1) 
     Next y 
    Next x 
End Sub 

工作表「主要」列C包含名稱的列表是A和B柱(姓和名)的串聯。這會導致我的程序無法運行?

工作表「名稱」列A包含人員名稱,而工作表「名稱」列B包含要複製到E列中工作表「主要」的數據(如果有匹配的話)。我是否以正確的方式去做這件事?

回答

1

使用嵌套循環搜索匹配可能非常低效。相反,請使用內置的.Find方法。請參閱下面的代碼以獲取示例,並告訴我們是否需要添加幫助。

Sub Find_Matches() 
    Dim compareRange As Range 
    Dim toCompare As Range 
    Dim rFound As Range 
    Dim cel As Range 

    Set compareRange = Worksheets("Names").Range("A1:A500") 
    Set toCompare = Worksheets("Main").Range("C1:C500") 
    Set rFound = Nothing 

    For Each cel In toCompare 
     Set rFound = compareRange.Find(cel) 
     If Not rFound Is Nothing Then 
      cel.Offset(, 2).Value = rFound.Offset(, 1) 
      Set rFound = Nothing 
     End If 
    Next cel 

End Sub 
+0

這個效果好多了,謝謝! –

相關問題