创建宏以仅将某些数据从一个工作表传输到另一个符合条件的工作表

时间:2018-05-31 20:13:12

标签: excel vba excel-vba

因此,我需要创建一个宏,根据工作表1中符合特定条件的不同列中的数据,将工作表1中列中特定单元格中的数据传输到工作表2。假设工作表1有一列(A),颜色为蓝色或绿色,另一列(B)有苹果或梨(苹果到蓝色和梨到绿色)。我需要创建一个宏,它只会将对应于蓝色的苹果转移到工作表2中的另一列。

Sub Update()
  Dim c As Range
  Dim j As Integer
  Dim Source As Worksheet
  Dim Target As Worksheet

    ' Change worksheet designations as needed
    Set Source = ActiveWorkbook.Worksheets("Sheet 2")
    Set Target = ActiveWorkbook.Worksheets("Sheet1")

    j = 1     ' Start copying to row 1 in target sheet
    For Each c In Source.Range("D35:D100")   
        If c = "Blue" Then
           Target.Range("C5").Value = Source.Range("B35")
           j = j + 1


        End If
    Next c

End Sub

无论我尝试什么,我都无法只传输符合“蓝色”标准的数据。任何帮助将非常感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

我假设您要将其复制到目标工作表的C列中...

Sub Update()
  Dim c As Range
  Dim j As Long
  Dim Source As Worksheet
  Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet 2")
Set Target = ActiveWorkbook.Worksheets("Sheet1")

j = 1     ' Start copying to row 1 in target sheet
For Each c In Source.Range("D35:D100")   
    If (c.Value = "Blue" And c.Offset(0.1).Value) = "Apples" Or _ 
(c.Value = "Green" And c.Offset(0,1).Value = "Pears") Then
       Target.Range("C" & j).Value = c.Value
       j = j + 1

    End If
Next c

End Sub