继我之前提出的上一个问题之后 - 我修改了Roy Cox编写的代码(感谢您节省了我很多时间!)来创建用户表单,以便在我创建的分析工具中添加,修改和删除用户的详细信息。
在单个工作表上处理用户数据时,它非常有效。
选择用户并单击“删除”将删除工作表上的用户数据。我修改了代码,以便在添加或删除用户时,它应检查每个工作表并相应地添加或删除行。
这是删除单张纸上的学生数据的代码:
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行的数据。它根本不会删除下一个工作表中的数据。
有人可以提供任何建议吗?
更改:
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
的工作表中的同一行,因为没有人再次设置c
并指向另一个工作表范围。
并简单地循环遍历Sheets集合不会更改活动工作表