首页 文章

excel:插入行更新公式

提问于
浏览
0

我尝试编写一个宏,双击一个单元格,在该单元格下面插入一个新的行与一些公式 . 对我来说重要的是,如果我再次双击单元格,则使用正确的索引更新先前插入的行的公式 .

例如,在下面的代码中,双击A1将在第2行中插入公式= B2 1 . 再次双击应在第2行插入相同的内容 . 但现在第2行移位到第3行,因此A3中的公式应为= B3 1 .

这是我到目前为止的代码:

Option Explicit

Const MYRANGE As String = "A:A"

Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    'If Sh.Name <> "Sheet1" Then Exit Sub
    If Target.Cells.Count > 1 Then Exit Sub
    If Intersect(Target, Sh.Range(MYRANGE)) Is Nothing Then Exit Sub
    Cancel = True
    Target.Rows(2).Insert
    Dim newRow As Range
    Set newRow = Target.Rows(2)
    Dim rowIndex As Long
    rowIndex = newRow.row
    newRow.Cells(1, 1).Formula = "=B" & rowIndex & "+1"
End Sub

更新:将 Target.Rows(2).Insert 更改为 Target.Offset(1).EntireRow.Insert 解决了问题 . 将问题留待解释什么是Offset以及它与Rows的区别(对于Rows(2),属性EntireRow不存在)

1 回答

  • 0

    对于相同的结果,您可以将此代码减少四行,请参阅下文

    请注意,您的代码正在更新目标行及其下方的单元格,即它不会更新位于目标上方的A列之外的任何单元格公式 . 这可能不是问题,但值得一提 . 如果您想要完整更新,那么您将始终在第2行而不是在目标处插入

    Option Explicit
    
    Const MYRANGE As String = "A:A"
    
    Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
        If Target.Cells.Count > 1 Then Exit Sub
        If Intersect(Target, Sh.Range(MYRANGE)) Is Nothing Then Exit Sub
        Cancel = True
        Target.Offset(1).EntireRow.Insert
        Target.Offset(1).Formula = "=B" & Target.Row + 1 & "+1"
    End Sub
    

相关问题