根据单元格条件将Sheet1的活动行复制到Sheet2(列F =“是”),并防止重复。 我尝试了以下
Private Sub CommandButton1_Click()
Dim CustomerName As String, Customeraddress As String, Customercity As String, Custtel As String, Custzip As String
Worksheets("sheet1").Select
CustomerName = Range("A2")
Customeraddress = Range("B2")
Customercity = Range("C2")
Custtel = Range("D2")
Custzip = Range("E2")
Worksheets("sheet2").Select
Worksheets("Sheet2").Range("B4").Select
If Worksheets("Sheet2").Range("B4").Offset(1, 0) <> "" Then
Worksheets("Sheet2").Range("B4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = CustomerName
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Customeraddress
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Customercity
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Custtel
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Custzip
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("C4").Select
End Sub
所以现在我需要知道如何检查该特定客户的sheet1列F =“是”。然后只从Sheet1复制到Sheet2。如果Sheet2中已存在客户信息,则如果用户单击sheet1活动行上的按钮,则不会复制。
答案 0 :(得分:1)
试试这段代码:
Private Sub CommandButton1_Click()
Dim lastrow As Long
'if value in column F not equal "YES" - do nothing and exit sub
If UCase(Range("F" & ActiveCell.Row).Value) <> "YES" Then Exit Sub
With ThisWorkbook.Worksheets("Sheet2")
lastrow = Application.Max(4, .Cells(.Rows.Count, "B").End(xlUp).Row + 1)
'if CustomerName is already in column B of sheet2 - do nothing and exit sub
If WorksheetFunction.CountIf(.Range("B1:B" & lastrow), _
Range("A" & ActiveCell.Row).Value) > 0 Then Exit Sub
.Range("B" & lastrow).Resize(, 5).Value = _
Range("A" & ActiveCell.Row).Resize(, 5).Value
End With
End Sub
并且,请阅读这篇文章:How to avoid using Select/Active statements:)