如何根据是否在Row3中select了一个单元格来跳过一些代码行?
我正在尝试用户select任何单元格,然后运行此macros的电子表格。 如果单元格不在第3行,那么select该单元格所在的整行,在第3行中剪切并插入该行。(这部分工作正常)如果选中的单元格在第3行,那么我想跳过剪切并插入部分代码。 这看起来应该很简单,但我得到的错误:如果没有阻止,如果我运行这个macros时结束。 任何帮助将不胜感激。 谢谢。
Dim Row As String ActiveCell.EntireRow.Select strRow = Selection If Selection = Rows("3:3") Then GoTo SkipToHere End If Selection.Cut ActiveWindow.SmallScroll Down:=-84 Rows("3:3").Select Selection.Insert Shift:=xlDown Range("A3").Select SkipToHere:
在这种情况下使用GoTo可能不是最好的办法。 相反,我只是将你的第一部分包装在一个If:
Dim strRow As String ActiveCell.EntireRow.Select strRow = Selection If Selection.Row <> 3 Then Selection.Cut Rows("3:3").Insert Shift:=xlDown Range("A3").Select End If
你也应该作为一个原则避免。select你不需要的地方。
在VBA中,可以用多种方式编写IF
语句:1.全部在一行上,或者2.用一个Else
组件,或者3.用ElseIf
…等等。
当你写这样的IF
语句:
If A=True Then B
没有Else
组件,那么VBA不需要End IF
语句。 当你像这样使用IF
时需要:
IF A=True Then Do this Else Do Something else End If
Dim Row As String If Activecell.Row = 3 Then GoTo SkipToHere End If ActiveCell.EntireRow.Select Selection.Cut ActiveWindow.SmallScroll Down:=-84 Rows("3:3").Select Selection.Insert Shift:=xlDown Range("A3").Select SkipToHere:
Sub Horsten()
“select和第三行没有任何意见?
If Intersect(Selection, Rows(3)) Is Nothing Then
然后剪切并粘贴(但不改变select)
Selection.EntireRow.Cut Rows(3).Insert Shift:=xlDown
“如果你喜欢,调整位置
ActiveWindow.SmallScroll Up:=84 Cells(3, 1).Select End If End Sub