Excel:数据粘贴后,替换单元格数据如果满足条件

时间:2018-03-23 11:06:11

标签: excel

这是我的Excel工作表:Excel Sheet Screenshot

因此,您从 A2 直到 H21 看到的数据会被客户粘贴。 我想做的是,一旦客户粘贴这些数据,就会发生以下情况:

B 等于" Brunch" H 等于0,用 J3 替换H

所以我们将使用 J3

中的值/数据代替0

每次客户将数据从 A2 粘贴到 H21

时,这应该自动完成

我真的很感激任何帮助,希望它清楚!

非常感谢

2 个答案:

答案 0 :(得分:0)

在标准代码模块中,如下所示。你可以看一下活动或只是按下按钮。

Option Explicit

Sub AddPrice()

    Dim wb As Workbook
    Dim ws As Worksheet

    Application.ScreenUpdating = False

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet2") 'change as appropriate

    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim filterRange As Range
    Set filterRange = ws.Range("$A$1:$H$" & lastRow)

    If lastRow = 1 Then Exit Sub

    With filterRange
       .AutoFilter
       .AutoFilter Field:=2, Criteria1:="Brunch"
       .AutoFilter Field:=8, Criteria1:="0"
    End With

    Dim currArea As Range
    Dim currRow As Range

    For Each currArea In filterRange.SpecialCells(xlCellTypeVisible).Areas
         For Each currRow In currArea.Rows
             If currRow.Row > 1 Then currRow.Cells(1, filterRange.Columns.Count) = ws.Range("J3")
         Next currRow
    Next currArea

    filterRange.AutoFilter

    Application.ScreenUpdating = True

End Sub

在表2的代码窗格中(在此示例中为put)

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

     Application.EnableEvents = False

    If Not Intersect(Target, Range("A1:H" & UsedRange.Rows.Count)) Is Nothing Then

        AddPrice

    End If

    Application.EnableEvents =True

End Sub

参考:

Automatically Run Macro When Data Is Pasted VBA

代码窗格表2:

Sheet2 code

标准模块代码:

Module code

答案 1 :(得分:0)

很抱歉得到了跟踪,但下面与QHarr的方法略有不同:

将以下代码复制到工作表代码中

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column < 8 Then
        Dim oWS As Worksheet: Set oWS = ThisWorkbook.Worksheets("Sheet8")
        Dim iLR As Long: iLR = oWS.Cells(oWS.Rows.count, "H").End(xlUp).Row
        Dim rHCol As Range: Set rHCol = oWS.Range("H2:H" & iLR)
        Dim rCurRange As Range

        With oWS
            For Each rCurRange In rHCol
                If (LCase(Trim(.Range("B" & rCurRange.Row).Value)) = "brunch") And (CInt(rCurRange.Value) = 0) Then
                    rCurRange.Value = .Range("J3")
                End If
            Next
        End With
    End If

End Sub