首页 > 解决方案 > 将新行添加到表 Excel VBA 时运行的宏

问题描述

我试图让我的宏仅在我的表添加了新行时运行。在有表格的工作表上,我包含了以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    'This module verifies row numbers in the database by matching them to the opportunities in the Projects
    'worksheet. It then assigns row numbers in the Projects worksheet.

    Dim Records As Range

    Set Records = Range("Records")
    If Not Application.Intersect(Records, Range(Target.Address)) Is Nothing Then
           Call FindRow       
    End If        
End Sub

这是FindRow代码:

Sub FindRow()
    'This module verifies row numbers in the database by matching them to the opportunities in the Projects
    'worksheet. It then assigns row numbers in the Projects worksheet.

    Application.ScreenUpdating = False
    Dim LastRow As Long
    LastRow = Sheets("Projects").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    Dim rng As Range
    Dim foundRng As Range
    For Each rng In Sheets("Projects").Range("B2:B" & LastRow)
        Set foundRng = Sheets("Database").Range("C:C").Find(rng, LookIn:=xlValues, lookat:=xlWhole)
        If Not foundRng Is Nothing Then
            rng.Offset(0, -1) = foundRng.Row
        End If
    Next rng
    Application.ScreenUpdating = True
End Sub

我最终得到一个应用程序定义或对象定义的错误LastRow = Sheets("Projects")...
这特别奇怪,因为过去的代码从未给我任何错误。

我能得到一些帮助吗?记录是目标表。数据库是另一张表上的表,宏在其中查找记录所在的行。另外,我应该使用Worksheet_TableUpdate而不是Worksheet_Change吗?例如看图片:

记录表示例

数据库表示例

标签: vbaexcel

解决方案


该行对我来说看起来不错,它一定是应用于没有名为“项目”的工作表的工作簿

我会声明您正在使用的工作簿并三重检查该工作簿中是否有一个名为“Projects”的工作表(没有空格或缺少 s 或类似的东西)

Dim wrkbook as workbook
    set wrkbook = Workbooks("WORKBOOKNAME")
    LastRow = Wrkbook.Sheets("Projects").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

推荐阅读