如果activecell.row小于某个数字,则停止宏工作

时间:2014-01-23 16:31:12

标签: vba excel-vba excel

我需要以下代码才能正常工作,任何帮助将不胜感激 我已经尝试了几个变种,但似乎无法让它工作

Sub INCOMENEWLINE()
'
' INCOMENEWLINE Macro
'

'
If ActiveCell.Row < 74 Then
    MsgBox "You cannot insert a new line here"
    Exit Sub
End If

If ActiveCell.Row > 73 Then
    ActiveSheet.Unprotect Password:="PB2014"
    Range("SAFILTER").AutoFilter
    Range("INCOMENEWLINE").Copy
    ActiveCell.EntireRow.Insert
    Selection.RowHeight = 13.5
    Range("SAFILTER").AutoFilter Field:=1, Criteria1:="O"
    Dim c As Range
    For Each c In Range("I5:J5")
        c.EntireColumn.Hidden = (c.Value = 0)
    Next c
Application.ScreenUpdating = True
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , Password:="PB2014"
    Exit Sub
End If

End Sub

2 个答案:

答案 0 :(得分:1)

在VBAProject-&gt; Microsoft Excel Objects-&gt; Sheet1(Sheet1)或您喜欢的任何工作表中使用此代码。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If ActiveCell.Row < 74 Then
        MsgBox "You cannot insert a new line here"
    Else
        'Insert the rest of your code here
    End If
End Sub

只要您选择更改,它就会自动运行。所以是的,把它放在你的Sheet代码中,而不是模块或用户表单。

你可能必须将他的宏分成这样的东西:

声明公共变量:

Public StopMacro as Boolean

然后有这个:

Sub SetStopMacro()

StopMacro = True

End Sub

最后:

Sub Macro1()
    While StopMacro is not False
        ''Do Stuff
        ''Do more stuff
        Exit sub ''This is if you don't want this code running over and over again
    Wend
End Sub

然后你会在Worksheet_SelectionChange子中调用SetStopMacro。

答案 1 :(得分:0)

尝试将activecell.row更改为selection.row