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
吗?例如看图片:
记录表示例
数据库表示例
解决方案
该行对我来说看起来不错,它一定是应用于没有名为“项目”的工作表的工作簿
我会声明您正在使用的工作簿并三重检查该工作簿中是否有一个名为“Projects”的工作表(没有空格或缺少 s 或类似的东西)
Dim wrkbook as workbook
set wrkbook = Workbooks("WORKBOOKNAME")
LastRow = Wrkbook.Sheets("Projects").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
推荐阅读
- c# - 根据ID计算总时间
- javascript - JavaScript 将数据分组到 2 层深的树视图中,最后一层是数组
- mysql - 加入动态表时是否使用索引?
- vim - 如何在 INSERT 模式下使用 vim 普通模式命令(遍历文本)
- java - DynamoDBAttribute 上的 AWS DynamoDB 约束
- javascript - javascript 常量行为
- python - 合并两个没有 on 参数的 dfs
- scala - 检查 spark 中是否存在嵌套列
- python-3.x - 使用 Keras 训练模型时出现内存不足错误
- django - Django 教程第 5 部分。Indexview 测试没有收到消息“没有可用的民意调查”。