【发布时间】:2021-03-16 11:12:32
【问题描述】:
我有一个 Excel 文件,我必须在其中一个工作表中输入名称,然后其他工作表添加或删除行。
例如,我有 Excel 表格 User、NumberSheet 和 GradeSheet。
我在 User-Sheet 中输入“John Doe”、“Jane Doe”和“Phil Doe”,在 NumberSheet 和 GradeSheet 中添加了 3 行。
我现在有这个代码:
Private Sub Worksheet_Change(ByVal Target As range)
Dim KeyCells As range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
' Start Cell is A2 because Names start there
Set KeyCells = range("A2:A100")
If Not Application.Intersect(KeyCells, range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
'The row in the user-Sheet, where I added or removed a user
targetRow = Target.row - 1
'In the Number Sheet, the row from where the names should get listed
targetRowInNumberSheet = targetRow
'The value from the cell where I entered the name
vlue = Target.Value
If IsEmpty(vlue) Then
'Delete row in Worksheets
Worksheets("NumberSheet").Rows(targetRowInNumberSheet).Delete
Worksheets("GradeSheet").Rows(targetRowInNumberSheet ).Delete
Else
'Add row in Worksheets
Worksheets("NumberSheet").Rows(targetRowInNumberSheet).Insert
Worksheets("GradeSheet").Rows(targetRowInNumberSheet ).Insert
End If
End If
End Sub
现在,如果我添加一个名称、删除一个名称或在其间某处插入一行,则此代码有效。
但是我不能删除多个名字,或者删除一行。在这两种情况下IsEmpty(vlue) 都是错误的,我不知道为什么
【问题讨论】:
-
在您的代码中,您是否尝试“删除多个名称”?
-
您的
Target范围能否包含更多单元格?