【发布时间】:2013-02-09 15:08:58
【问题描述】:
我想知道是否有人可以帮助我。
几周以来,我一直在尝试寻找一种解决方案,让用户可以执行以下操作:
- 删除有数据和没有数据的行,
- 移动所有包含数据的行,使它们并排放置,
- 同时保持定义的“输入范围”
我整理了以下脚本,它清除单元格内容,因此不会改变“输入范围”。
Sub DelRow()
Dim msg
Sheets("Input").Protect "handsoff", userinterfaceonly:=True
Application.EnableCancelKey = xlDisabled
Application.EnableEvents = False
msg = MsgBox("Are you sure you want to delete this row?", vbYesNo)
If msg = vbNo Then Exit Sub
With Selection
Application.Intersect(.Parent.Range("A:S"), .EntireRow).Interior.ColorIndex = xlNone
Application.Intersect(.Parent.Range("T:AE"), .EntireRow).Interior.ColorIndex = 42
Selection.SpecialCells(xlCellTypeConstants).ClearContents
Application.Intersect(.Parent.Range("C:AE"), .EntireRow).Locked = True
Application.Intersect(.Parent.Range("AG:AG"), .EntireRow).Locked = True
End With
Application.EnableEvents = True
End Sub
更新代码
Sub DelRow()
Dim RangeToClear As Range
Dim msg As VbMsgBoxResult
'Sheets("Input").Protect "handsoff", userinterfaceonly:=True
Application.EnableCancelKey = xlDisabled
Application.EnableEvents = False
msg = MsgBox("Are you sure you want to delete this row?", vbYesNo)
If msg = vbNo Then Exit Sub
With Selection
Application.Intersect(.Parent.Range("A:S"), .EntireRow).Interior.ColorIndex = xlNone
Application.Intersect(.Parent.Range("T:AE"), .EntireRow).Interior.ColorIndex = 42
On Error Resume Next
Set RangeToClear = Selection.SpecialCells(xlCellTypeConstants)
On Error GoTo 0 ' or previously defined error handler
If Not RangeToClear Is Nothing Then
RangeToClear.ClearContents
Else
Selection.Sort Key1:=Range("B7"), Order1:=xlAscending, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End If
Application.Intersect(.Parent.Range("C:AE"), .EntireRow).Locked = True
Application.Intersect(.Parent.Range("AG:AG"), .EntireRow).Locked = True
End With
Application.EnableEvents = True
End Sub
但问题在于,如果用户选择空白行,他们会收到“错误 400”消息,并且不会将行向上移动以位于彼此下方。
正如我所说,我花了很多时间试图找到解决方案,但没有任何成功。
如果有人能看到这个并就我如何实现这一目标提供一些指导,我将非常感激。
非常感谢和亲切的问候
【问题讨论】:
-
根据support.microsoft.com/?kbid=146864 运行时错误 400 是“表单已显示;无法以模态方式显示”至少在 Excel 97 中(!)。这似乎不适用。
ClearContents行有错误吗?错误的措辞是什么? -
嗨@DougGlancy,感谢您抽出宝贵时间回复我的帖子。错误只是说“400”。如果有帮助,我在这里设置了一个测试文件:box.com/s/cnptwwmnmzoooirrgos2。您会看到在第 8-11 行中,B 列中有数据。然后我将数据添加到第 46 行和第 47 行,再次在 B 列中。如果您突出显示中间的空白行并尝试删除它们,您将收到有问题的错误。非常感谢和亲切的问候
-
好吧,我看到一个错误,如果选择为空白,您的
ClearContents行,所以我会回答这个问题,看看它是否有帮助。 -
所以,如果您清除内容,听起来您想要排序。这意味着排序代码不应位于 Else 子句中,而应位于 If 子句中。我会再次尝试修改我的答案以获得你想要的。
-
嗨@DougGlancy,谢谢,是的,如果可能的话,这就是我想要实现的目标。亲切的问候
标签: excel excel-2003 vba