将新行添加到表Excel VBA时运行的宏

时间:2018-05-15 00:33:46

标签: excel vba 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吗? 例如,参见图片:

记录表示例

数据库表示例

1 个答案:

答案 0 :(得分:1)

这条线对我来说看起来不错,它必须是在没有Sheet命名的工作簿上应用#34; Projects"

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

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