[英]VBA Excel - Auto run macro to insert new blank row after cell above has value entered
I am trying to get a macro to auto run to: 我正在尝试让宏自动运行到:
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
I think I can help you with your first question. 我想我可以为您解决第一个问题。
You can automatically start a macro when a cell changes with a Sub Worksheet_Change(ByVal Target As Range)
Sub inside the worksheet. 当单元格随着
Sub Worksheet_Change(ByVal Target As Range)
的Sub Worksheet_Change(ByVal Target As Range)
Sub发生变化时,您可以自动启动宏。
Here is description: https://support.microsoft.com/en-us/help/213612/how-to-run-a-macro-when-certain-cells-change-in-excel 这是描述: https : //support.microsoft.com/en-us/help/213612/how-to-run-a-macro-when-certain-cells-change-in-excel
You can insert a new row with the following code: 您可以使用以下代码插入新行:
Application.Selection.EntireRow.Insert shift:=xlDown
When you do just that, you will encounter that the new line will again trigger the event to start the macro, hence again inserting a new line. 当您这样做时,您会遇到新行将再次触发事件以启动宏,因此再次插入新行。 This leads to an infinity loop.
这导致无限循环。 To stop this from happening, we need to disable events for the time of the change.
为了阻止这种情况的发生,我们需要在更改期间禁用事件。
Application.EnableEvents = False
Call new_line_below_selection_macro
Application.EnableEvents = True
Here is a question with a similar problem: How to end infinite "change" loop in VBA 这是一个带有类似问题的问题: 如何结束VBA中的无限“更改”循环
I hope this helps. 我希望这有帮助。
Here is the code which should go into the sheet: 这是应该放在工作表中的代码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.