删除多个工作表上的行

时间:2018-09-11 12:34:38

标签: excel vba delete-row

根据我今天问的上一个问题-我已经修改了Roy Cox编写的代码(感谢您为我节省了很多时间!)以创建一个用户表单,以便在分析工具I中添加,修改和删除用户的详细信息正在创建。

当在单个工作表上处理用户数据时,它完美地工作。

选择用户并单击“删除”会在工作表上删除其用户数据。我已经修改了代码,以便在添加或删除用户时,它应该检查每个工作表并相应地添加或删除行。

这是用于删除单张纸上的瞳孔数据的代码:

Private Sub cmbDelete_Click()

Dim msgResponse As String    'confirm delete

Application.ScreenUpdating = False

'get user confirmation
msgResponse = MsgBox("This will delete the selected record. Continue?", _
    vbCritical + vbYesNo, "Delete Entry")
Select Case msgResponse    'action dependent on response

Case vbYes
'c has been selected by Find button on UserForm
Set c = ActiveCell
    c.EntireRow.Delete    'remove entry by deleting row

'restore form settings
With Me
    .cmbAmend.Enabled = False    'prevent accidental use
    .cmbDelete.Enabled = False    'prevent accidental use
    .cmbAdd.Enabled = True    'restore use
    'clear form
    Call ClearControls
End With

Case vbNo
Exit Sub    'cancelled
End Select

Application.ScreenUpdating = True

End Sub

我试图修改它,以删除每个工作表上的用户数据,如下所示:

Private Sub cmbDelete_Click()

Dim Sh As Worksheet
Dim msgResponse As String    'confirm delete

Application.ScreenUpdating = False

'get user confirmation
msgResponse = MsgBox("This will delete the selected record. Continue?", _
    vbCritical + vbYesNo, "Delete Entry")
Select Case msgResponse    'action dependent on response

Case vbYes
For Each Sh In ThisWorkbook.Sheets
With Sh.UsedRange
    'c has been selected by Find button
    Set c = ActiveCell
        c.EntireRow.Delete    'remove entry by deleting row
End With
Next

'restore form settings
With Me
    .cmbAmend.Enabled = False    'prevent accidental use
    .cmbDelete.Enabled = False    'prevent accidental use
    .cmbAdd.Enabled = True    'restore use
    'clear form
    Call ClearControls
End With

Case vbNo
Exit Sub    'cancelled
End Select

Application.ScreenUpdating = True

End Sub

但是此版本删除用户的数据及其下面4行中的数据。它根本不会从下一个工作表中删除数据。

任何人都可以提供任何建议吗?

1 个答案:

答案 0 :(得分:1)

更改:

Case vbYes
    For Each Sh In ThisWorkbook.Sheets
    With Sh.UsedRange
        'c has been selected by Find button
        Set c = ActiveCell
            c.EntireRow.Delete    'remove entry by deleting row
    End With
    Next

收件人:

Case vbYes
    Dim l As Long
    l = ActiveCell.Row 'store currently active cell row
    For Each Sh In ThisWorkbook.Worksheets
        Sh.Rows(l).Delete
    Next

您是否有兴趣知道为什么以前的代码不起作用:

1)

Set c = ActiveCell

c设置为当前活动单元格,即您在当前活动工作表中选择的“查找”按钮的单元格

2)而

c.EntireRow.Delete

总是,毫无意外地,删除c 整行,即在工作表中找到c的同一行,因为没有人设置{{1 }},然后指向另一个工作表范围。

,仅循环遍历Sheets集合并不会更改 Active 工作表