VB宏在两个工作表中比较4个字段然后粘贴一个值

时间:2017-06-04 07:23:34

标签: vba

我是VB的新手,所以你能提供的任何帮助都会很棒。我有两个工作表。它们在两张纸之间有四个共同的字段。这些行将包含更多不匹配的字段。如果四个字段匹配,那么我需要将两个字段粘贴到第二个表中。

虽然这有效但它是硬编码的,我必须为每一行做这个。

我想创建一个双循环,并允许行上的四个字段与每行的第二个表格进行比较,以查看是否存在匹配。如果是这样,它将粘贴两个字段,它将继续到第一个工作表中的下一行并再次执行该过程。

If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
   If [w2.Range.("d2")] = [w1.Range.("c3")] Then
     w1.Select
     Range("N3:O3").Select
     Selection.Copy
     w2.Select
     Range("G2:H2").Select
     ActiveSheet.Paste
 End If
 End If
 End If

任何帮助都会很棒。

我得到了两张纸,基本上是比较。我现在唯一的问题是如何循环和递增而不是下一行。

Sub Macro1()
'
' Macro1 Macro
'
Set w1 = Worksheets("DDR_Mar'17")
Set w2 = Worksheets("Release DrillDown")
Dim drea As String
Dim seva As String

SelRow = Selection.Row

'category ITSR on "DDR_Mar'17" sheet
   itsra = w1.Cells(SelRow, 7)
'category Application on "DDR Mar'17" sheet
   appa = w1.Cells(SelRow, 2)
'category SubCategory on "DDR Mar'17" sheet
   scata = w1.Cells(SelRow, 3)
'category DRE on "DDR Mar'17" sheet
   drea = w1.Cells(SelRow, 14)
'category SEV on "DDR Mar'17" sheet
   seva = w1.Cells(SelRow, 15)


lr = w1.Cells(Rows.Count, 1).End(xlUp).Row

SelRow = Selection.Row
'category ITSR on "Release Drilldown" sheet
   itsrb = w2.Cells(SelRow, 2)
'category Application on "Release Drilldown" sheet
   appb = w2.Cells(SelRow, 3)
'category SubCategory on "Release Drilldown" sheet
   scatb = w2.Cells(SelRow, 4)
'category DRE on "Release Drilldown" sheet
   dreb = w2.Cells(SelRow, 7)
'category SEV on "Release Drilldown" sheet
 '  sevb = w2.Cells(SelRow, 8)

lr2 = w2.Cells(Rows.Count, 1).End(xlUp).Row


For x = 1 To lr2
   w2.Cells(x, 1) = x
 For y = 1 To lr
   w1.Cells(y, 1) = y

  If itsra = itsrb Then
    If appa = appb Then
     If scata = scatb Then
          w = w + 1
  End If
  End If
  End If

Next y
Next x

End Sub

2 个答案:

答案 0 :(得分:0)

您可以使用for循环遍历测试值的每一行

Dim trange As Range
Set trange = w2.Range("B2:D4") 'Range you're testing
For Each trow In trange.Rows
    If trow.Columns(1) = w1.Range("G3") _
    And trow.Columns(2) = w1.Range("B3") _
    And trow.Columns(3) = w1.Range("C3") Then
        w1.Range("N3:O3").Copy Destination:=trow.Offset(0, 5)
        Exit For
    End If
Next

如果你也想要循环浏览w1,你可以设置第二个范围并嵌套for eaches

For each trow In trange.rows
     For each rrow in rrange.rows
         if trow.column(1) = rrow.column(1) And ect....

答案 1 :(得分:0)

我认为Select方法不是gooo。

If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
        If [w2.Range.("d2")] = [w1.Range.("c3")] Then
            w2.Range("G2:H2").Value = w1.Range("N3:O3").Value
        End If
    End If
 End If