![](/img/trans.png)
[英]Excel Macro to change cell alignment, borders and wrap text if a value has been entered into another cell in the same row
[英]VBA Excel - Auto run macro to insert new blank row after cell above has value entered
我正在嘗試讓宏自動運行到:
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
我想我可以為您解決第一個問題。
當單元格隨着Sub Worksheet_Change(ByVal Target As Range)
的Sub Worksheet_Change(ByVal Target As Range)
Sub發生變化時,您可以自動啟動宏。
這是描述: https : //support.microsoft.com/en-us/help/213612/how-to-run-a-macro-when-certain-cells-change-in-excel
您可以使用以下代碼插入新行:
Application.Selection.EntireRow.Insert shift:=xlDown
當您這樣做時,您會遇到新行將再次觸發事件以啟動宏,因此再次插入新行。 這導致無限循環。 為了阻止這種情況的發生,我們需要在更改期間禁用事件。
Application.EnableEvents = False
Call new_line_below_selection_macro
Application.EnableEvents = True
這是一個帶有類似問題的問題: 如何結束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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.