简体   繁体   English

excel vba-宏可在单元格更改时复制过滤的数据

[英]excel vba - Macro to copy filtered data on cell change

I'm trying to write a macro to do the following: 我正在尝试编写一个宏来执行以下操作:

  • from Sheet1 watch the A column for the data I input; 从Sheet1看A列中我输入的数据;
  • when I write something in a cell in the A column use that value to filter Sheet2; 当我在A列的单元格中写入内容时,使用该值过滤Sheet2;
  • after the filter is done, copy everything except the column header from the second sheet into the first one, even if there are multiple values; 过滤完成后,将列标题以外的所有内容从第二张工作表复制到第一张工作表中,即使有多个值也是如此;
  • as a bonus it could copy everything except from column A from Sheet2 and copy starting from Column B in Sheet1, which is what I attempted. 作为奖励,它可以从Sheet2复制A列以外的所有内容,并从Sheet1的B列开始复制,这就是我的尝试。

I tried writing this: 我试着这样写:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A:A")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        MsgBox "Cell " & Target.Address & " has changed. New value is: " _
            & Target.Value
        copy_filter (Target)
    End If
End Sub

Sub copy_filter(Changed)
    Worksheets("Sheet2").Select

    With Worksheets("Sheet2")
        With .Range("$A$1:$L$5943")
            .AutoFilter Field:=1, Criteria1:=Changed.Value
            .SpecialCells(xlCellTypeVisible).Select
            Selection.Offset(1, 0).Copy
        End With
    End With

    Worksheets("Sheet1").Select
    Worksheets("Sheet1").Range(Changed.Address).Offset(0, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False
End Sub

The first Private Sub watches for change events on Sheet1, I put it into the sheet module, not the Workbook module, and it works, since the box gets shown correctly, however on the second Sub I get an error on this line: .AutoFilter Field:=1, Criteria1:=Changed.Value , the error says: Run-time error '424': Object required . 第一个Private Sub监视Sheet1上的更改事件,我将其放入工作表模块中,而不是工作簿模块中,并且可以正常工作,因为该框正确显示,但是在第二个Sub我在此行出现错误: .AutoFilter Field:=1, Criteria1:=Changed.Value ,错误显示: Run-time error '424': Object required

I can't figure out what I'm doing wrong. 我不知道我在做什么错。

Change copy_filter (Target) to either copy_filter (Target)更改为

call copy_filter (Target)

OR 要么

copy_filter Target

Read this: https://msdn.microsoft.com/en-us/library/office/gg251432.aspx 阅读此: https : //msdn.microsoft.com/en-us/library/office/gg251432.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM