【问题标题】:compare ranges and populate values in VBA Macro在 VBA 宏中比较范围并填充值
【发布时间】:2017-06-07 11:34:18
【问题描述】:

我正在尝试编写一个宏来比较 Excel 中的两个范围 Rng1 和 Rng2。 Rng1 ("f2:f15") 包含正在使用的目标编号。 Rng2 ("a2:a91") 包含所有可能目标的数字。 Rng2 右侧的三列 ("b2:b91")、("c2:c91") 和 ("d2:d91") 包含与每个目标编号关联的 x、y 和 z 坐标值。我希望这个宏做的是用坐标值填充 Rng1 右侧的 3 列,("g2:g15")、("h2:h15") 和 ("i2:i15")在 Rng1 中找到的目标编号。我编写的以下代码正在重新调整“运行时错误'13',类型不匹配”。

Sub macro()
Dim Rng1 As Range, Rng2 As Range, Cell1 As Range, Cell2 As Range
Set Rng1 = Range("f2:f15")
Set Rng2 = Range("a2:a91")
For i = 1 To Rng1
    For j = 1 To Rng2
        For Each Cell1 In Rng1(i)
            For Each Cell2 In Rng1(j)
               If Cell1.Value = Cell2.Value Then
                'cell1.Offset(0, 1) = cell2.Offset(0, 1)
                'cell1.Offset(0, 1) = cell2.Offset(0, 1)
                'cell1.Offset(0, 1) = cell2.Offset(0, 1)
                Cells(2 + i, 7) = Cells(2 + j, 2)
                Cells(2 + i, 8) = Cells(2 + j, 3)
                Cells(2 + i, 9) = Cells(2 + j, 4)
             End If
          Next Cell2
       Next Cell1
     Next j
  Next i

End Sub

谢谢!

【问题讨论】:

  • 用文字写出你想要用For I = 1 to Rng1 语句实现的目标。您希望Rng1(1) 中有多少个 Cell?
  • 我试图使用 I = 1 到 Rng1 作为计数器来跟踪 Rng1 中的值,因为我试图使用 j 作为计数器来跟踪 Rng2 中的值。我不是一个非常有经验的编码员,可能做得非常不正确。谢谢!
  • 但是 Rng1 是一个多单元格范围对象。所以一个循环从 1 运行到 ??没有意义。这就是您收到类型不匹配错误的原因。查看 For ...Next 循环的 VBA 帮助。然后,稍后,你有For each cell in Rng1(i)。如果 I = 1,则 Rng1(I) 将是该范围内的第一个单元格。同样,Rng1(I) 中的每个单元格将只有一个单元格。您可能可以完全消除 Ij 循环,并且仍然循环遍历范围中的每个单元格。

标签: excel compare range populate


【解决方案1】:

根据您的描述,我认为这就是您想要的

Sub Demo()
    Dim Rng1 As Range, Rng2 As Range, Cell1 As Range
    Dim i As Variant
    Set Rng1 = Range("f2:f15")
    Set Rng2 = Range("a2:a91")

    '  Loop over the cells you want to add data for
    For Each Cell1 In Rng1
        ' locate current value in range 2
        i = Application.Match(Cell1.Value, Rng2, 0)
        If Not IsError(i) Then
            ' if found copy offset data
            Cell1.Offset(0, 1) = Rng2.Cells(i, 2)
            Cell1.Offset(0, 2) = Rng2.Cells(i, 3)
            Cell1.Offset(0, 3) = Rng2.Cells(i, 4)
        End If
    Next
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多