【问题标题】:VBA Excel - Auto run macro to insert new blank row after cell above has value enteredVBA Excel - 自动运行宏以在上面的单元格输入值后插入新的空白行
【发布时间】:2017-06-09 18:24:30
【问题描述】:

我正在尝试让宏自动运行到:

  1. 在每个部分中插入一个空白行,例如当上面的数据验证行(在 A 列中)输入了一个值时的架构。 我在工作表中将代码作为子输入,当我在 excel 的开发人员选项卡中单击运行时,它会插入一行,但我希望它在每次输入内容时自动运行(打开工作簿后)列答:

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

【问题讨论】:

  • 你的代码有什么问题?请删除On Error Resume Next,它只会使错误静音,这样您就看不到它们并运行您的代码。 edit您的问题并添加您的代码实际执行的操作以及您期望它执行的操作以及是否有任何错误消息在哪里发生?
  • 你需要寻找一个事件,在 worksheet.change 事件或类似的东西上运行你的宏。

标签: vba excel


【解决方案1】:

我想我可以帮你解决你的第一个问题。

当单元格发生变化时,您可以自动启动宏,并在工作表中使用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

这里有一个类似问题的问题: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

【讨论】:

  • 好的,谢谢@Axel。抱歉,我对 VBA(或实际上的任何编码)和 Stack Overflow 非常陌生。我的原始代码应该作为工作表中的子代码还是模块?
  • 您好,您可以将代码放在模块中并通过Call module1.BlankLine 从工作表中调用它,或者将整个代码粘贴到工作表中。将 sub 写入模块可能更简洁,并且可以让您在其他地方重用它。
  • 我收到编译错误:外部过程无效
  • 我在答案中添加了另一段代码,希望它更清楚
猜你喜欢
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多