我想让一个宏自动运行到:
Sub BlankLine()
'Updateby20150203
Dim Rng As Range
Dim WorkRng As Range
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Set WorkRng = WorkRng.Columns(1)
xLastRow = WorkRng.Rows.count
Application.ScreenUpdating = False
For xRowIndex = xLastRow To 1 Step -1
Set Rng = Range("B" & xRowIndex)
If Rng.Value = "" = False Then
Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown
End If
Next
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
我想我可以帮你解决第一个问题。
当单元格在工作表中使用Sub Worksheet_Change(ByVal Target As Range)
Sub更改时,您可以自动启动宏。
您可以使用以下代码插入新行:
Application.Selection.EntireRow.Insert shift:=xlDown
当您这样做时,您将遇到新行将再次触发事件以启动宏,因此再次插入新行。这导致无限循环。要阻止这种情况发生,我们需要在更改时禁用事件。
Application.EnableEvents = False
Call new_line_below_selection_macro
Application.EnableEvents = True
以下是一个类似问题的问题:How to end infinite "change" loop in VBA
我希望这会有所帮助。
以下是应该进入工作表的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("A1:C10") 'Area this should apply
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
Application.EnableEvents = False
'either you put your code here
'Application.Selection.EntireRow.Insert shift:=xlDown
'or you call it from a module
Call Module1.BlankLine
Application.EnableEvents = True
End If
End Sub