简体   繁体   English

在Excel VBA中,如果存在匹配项,如何比较两个范围并将一个范围的偏移量复制到另一个范围的偏移量?

[英]In Excel VBA, how can I compare two ranges and copy an offset of one range into an offset of another if there's a match?

After some googling, I'm using the below: 经过一番谷歌搜索后,我正在使用以下内容:

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

Worksheet "main" column C contains a list of names that is a concatenation of the A and B columns (first and last names). 工作表的“主”列C包含一个名称列表,该名称列表是A和B列的串联(名字和姓氏)。 Would this cause my program to not run? 这会导致我的程序无法运行吗?

Worksheet"names" column A contains names of people, and Worksheet"names" column B contains the data I want to copy to Worksheet"main" in column E if there's a match. 如果存在匹配项,则工作表“名称”列A包含人员名称,工作表“名称”列B包含我要复制到E列中工作表“ main”的数据。 Am I going about this the right way? 我要这样做正确吗?

Using nested loops to search for a match can be terribly inefficient. 使用嵌套循环搜索匹配项可能会非常低效。 Instead, use the built-in .Find method. 而是使用内置的.Find方法。 See the below code for an example, and let us know if you need added help working with it. 请参见下面的代码作为示例,如果您需要使用它的更多帮助,请告诉我们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM