首页 > 解决方案 > Excel VBA复制匹配条件单元格并根据不同工作表中的条件粘贴到特定单元格中

问题描述

我正在尝试在单元格中搜索特定文本并将其复制到新创建的列表中。我需要比较这些值并且从未使用过 VBA。下面是搜索和复制值的条件示例。

旧参数表 新参数表

在 Newparam 表中,L 列需要填充 OldParam 表 L 列中匹配的文本,基于以下示例;

当名称为 20M408 和 20M408_1 时,在 NewParam 中,如果 F 列 = st1CLOSE,仅当 G 列 = OFFNRM 时,才从 OldParam 列 L 复制文本。如果名称和带有 OFFNRM 的 st1CLOSE 之间不匹配,则 NewParam 列 L 用 N/A 填充。以上对20M409等重复。

谢谢你。

标签: excelvba

解决方案


我已经尝试过下面的代码,但是当找到匹配项时,我无法获得匹配的行号(对于 K = )。

Sub match()
 Dim s1 As Worksheet, s2 As Worksheet
 Dim I As Long, J As Long, K As Long, L As Long, M As Long, NewName As String, NewValue As String
  
 Set s1 = Sheets("Report")
 Set s2 = Sheets("Sheet1")
 K = 1
 M = 1
 I = s1.Cells(Rows.Count, "A").End(xlUp).Row
 L = s2.Cells(Rows.Count, "A").End(xlUp).Row

 For M = 2 To L
 
    If s2.Cells(M, "F").Value = "st1 CLOSE" Then
        NewName = s2.Cells(M, "B").Value
                  
        For K = 2 To I
        
            If s1.Cells(K, "K").Value = "OFFNRMPR" And s1.Cells(K, "A").Value = NewName Then
                s1.Cells(K, "L").Copy s2.Cells(M, "L").Value
                Exit For
            Else: s2.Cells(M, "L").Value = "N/A"
                Exit For
            End If
        Next
    End If
 Next
End Sub


推荐阅读