将列复制到 Excel 中的新工作表

问题描述 投票:0回答:1

我有一个电子表格,但有一些代码不起作用。

我需要根据 K 列是否已填充(带有日期)将数据行复制到另一张工作表。

代码停止了,我不知道为什么(我不是很好)。

我可以附上表格 - 代码是:

Private Sub Workbook_Open()
    Dim rng As Range, cell As Range, lastRow As Long
    Dim wsPaid      As Worksheet: Set wsPaid = ThisWorkbook.Worksheets("Paid")
    Application.ScreenUpdating = False

    If Not Intersect(Target, Me.Columns("K")) Is Nothing Then
        Application.EnableEvents = False

        For Each cell In Target
            
            If IsDate(cell.Value) Then
                Set rng = Intersect(Target.EntireRow, Me.Range("A:M"))
                lastRow = wsPaid.Cells(wsPaid.Rows.Count, "A").End(xlUp).Row + 1
                rng.Copy wsPaid.Range("A" & lastRow)
                wsPaid.Cells.Columns.AutoFit
                rng.Delete
            End If

        Next cell

        Application.EnableEvents = True
    End If

    Application.ScreenUpdating = True
End Sub

我尝试了代码,但它停在 If Not Intersect(Target, Me.Columns("K")) Is Nothing Then

所以我没有走远。 K 列是示例中的付费列,第一个条目(突出显示)是我想要转到第二张表的示例。

我希望它在每次打开时运行,对于新条目,然后转到第二张表的底部。床单分别为未付和已付。

任何关于我做错的事情的帮助将不胜感激。

Sample data

excel vba
1个回答
0
投票

正如 @taller 评论的那样,这是工作簿的打开事件中的改编代码。

Me
更改为相应的工作表名称。

Private Sub Workbook_Open()
    Dim rng As Range, cell As Range, lastRow As Long
    Dim wsPaid As Worksheet: Set wsPaid = ThisWorkbook.Worksheets("Paid")
    Dim wsLookup As Worksheet: Set wsLookup = Worksheets("Unpaid") 'change to the actual name of  the sheet
    Application.ScreenUpdating = False

        Application.EnableEvents = False

        For Each cell In wsLookup.Columns("K").Cells
            
            If IsDate(cell.Value) Then
                Set rng = Intersect(cell.EntireRow, wsLookup.Columns("A:M"))
                lastRow = wsPaid.Cells(wsPaid.Rows.Count, "A").End(xlUp).Row + 1
                rng.Copy wsPaid.Range("A" & lastRow)
                wsPaid.Cells.Columns.AutoFit
                rng.Delete
            End If

        Next cell

        Application.EnableEvents = True

    Application.ScreenUpdating = True
End Sub

注意:要加快该过程,您可以限制列实际范围的

Columns("K")
范围,例如类似于
lastrow
wsPaid.Range("A" & lastRow)
,但现在针对 K 列。

© www.soinside.com 2019 - 2024. All rights reserved.