Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用VBA在多个Excel工作表中添加或删除行_Excel_Vba - Fatal编程技术网

如何使用VBA在多个Excel工作表中添加或删除行

如何使用VBA在多个Excel工作表中添加或删除行,excel,vba,Excel,Vba,我有一个Excel文件,在其中我必须在一个工作表中输入名称,然后其他工作表添加或删除行 例如,我有excel表格用户,数字表和成绩表 我在用户表中输入“John Doe”、“Jane Doe”和“Phil Doe”,在数字表和成绩表中添加了3行 我现在有这个代码: Private Sub Worksheet_Change(ByVal Target As range) Dim KeyCells As range ' The variable KeyCells contains the cells

我有一个Excel文件,在其中我必须在一个工作表中输入名称,然后其他工作表添加或删除行

例如,我有excel表格
用户
数字表
成绩表

我在用户表中输入“John Doe”、“Jane Doe”和“Phil Doe”,在数字表和成绩表中添加了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)
将为false,我不知道为什么
IsEmpty
不检查单元格值是否为空

它检查变量是否已初始化

如果IsEmpty(vlue)则使用simple,而不是
,请使用:

If vlue = "" Then
或:

请检查Microsoft如何描述此功能

然后,建议声明所有使用的变量(
targetRow
targetRowNumberSheet
vlue
)。 如果
目标
必须只包含一个单元格,则应添加代码行:

If Target.count>1 then Exit Sub

如果您想允许多个单元格的范围,您应该声明它,并以不同的方式处理您尝试执行的操作。我问过,但你什么也没回答。如果是这样,我可以告诉您如何继续。

这是因为工作表更改函数的输入参数是一个称为Target的范围

范围是一个区域,而不是单个值。 如果现在删除多行,则Target.Row属性仅返回目标范围内的第一行,因此仅删除第一个条目

因此,您应该进一步查找有关范围的信息

我想试试这个: 计算目标范围内的所有行数:

Target.Rows.Count
使用此数字,您可以从范围的第一行索引继续,就像您的示例中的循环或其他内容:

 targetRow = Target.row - 1

在您的代码中,您是否尝试“删除多个名称”?您的
目标范围是否可以包含更多单元格?
 targetRow = Target.row - 1