【问题标题】: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?在 Excel VBA 中,如果有匹配项,如何比较两个范围并将一个范围的偏移量复制到另一个范围的偏移量中?
【发布时间】:2015-09-01 21:45:29
【问题描述】:

经过一番谷歌搜索,我正在使用以下内容:

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 列中的工作表“主”的数据(如果有匹配项)。我会以正确的方式解决这个问题吗?

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2020-11-06
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多