根据条件

时间:2015-08-04 05:30:11

标签: excel-vba vba excel

我编写了一个宏代码来复制一个工作表(Sheet2)中的数据并粘贴到另一个工作表(Sheet1)上。这很好用。但是,我想有一个条件来确定在Sheet1中粘贴数据的位置。 条件是,如果在Sheet2中的单元格A1中选择(从下拉列表),在Sheet1中的A列(已复制数据)中找到该国家/地区,请使用最新数据更新(覆盖)该国家/地区数据,否则如果是它应该将新数据粘贴到Sheet1上的最后一组数据下面。

这是我到目前为止编写的代码:

Private Sub CommandButton1_Click()
ActiveSheet.Range("A1:F44").Copy
    With Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
        .PasteSpecial xlPasteFormats
    ActiveSheet.Range("A1:F44").Copy
    With Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
        .PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Sheets("Sheet2").Activate
End With
End With
End Sub

任何帮助都将受到高度赞赏!非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以在A列上使用match功能来检查您是否已经拥有该国家/地区。如果匹配返回一个数字,使用它来替换国家数据,否则,它将返回错误 - 捕获它并在工作表的末尾添加数据。 我不确定你的数据究竟是如何看待你所写的,但这就是你想要在genral中做的事情。

一般的approch将是: 我正在使用匹配来查找行值,并且iferror以确保我没有收到错误。

country = Worksheets("Sheet1").Cells(1, "A").Value 'or where your drop down is
    test = Application.WorksheetFunction.IfError(WorksheetFunction.Match(country, "A:A", 0), -1)
    If test = -1 Then
        'copy to end of sheet
    Else
         *with sheets(Sheet1).cells(rows.value, test).end(xlup).offset(1,0)* 
        'copy to the value in test - it's the row number of the country we are copying now
    End If