更改事件上的VBA在扩展行时会破坏ListObjectTable

时间:2016-01-07 13:54:53

标签: excel vba excel-vba

我的代码使用listobject.table,旨在允许编辑价格和计算折扣,反之亦然...... 在进入单元格进行编辑时,将其中的公式转换为值,并将公式粘贴到另一列中。

当用户编辑单元格时,它就像一个魅力。但是,如果用户尝试向listobject.table添加行,则宏会破坏表。它添加了几列,并替换了一些标题。

是否可以以某种方式使宏忽略添加新行或扩展data.table范围的操作?

这是宏,感谢各位朋友的建议:

Private oListObj As ListObject

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

Set oListObj = Worksheets("Quotation").ListObjects("tblProForma")

Application.EnableEvents = True

    If Not Intersect(Target, oListObj.ListColumns("Price").DataBodyRange) Is Nothing Then
    Application.EnableEvents = False
    Application.AutoCorrect.AutoFillFormulasInLists = False
    Target.Formula = Target.Value
    Application.EnableEvents = True
    End If

    If Not Intersect(Target, oListObj.ListColumns("Discount").DataBodyRange) Is Nothing Then
    Application.EnableEvents = False
    Application.AutoCorrect.AutoFillFormulasInLists = False
    Target.Formula = Round(Target.Value, 5)
    Application.EnableEvents = True
    End If

End Sub



Private Sub Worksheet_Change(ByVal Target As Range)

Dim PriceDiscountOffset As Integer: PriceDiscountOffset = ActiveSheet.Range("tblProForma[[#All],[Price]:[Discount]]").Columns.Count - 1

Set oListObj = Worksheets("Quotation").ListObjects("tblProForma")

Application.EnableEvents = True


    If Not Intersect(Target, oListObj.ListColumns("Price").DataBodyRange) Is Nothing Then
    Application.EnableEvents = False
    Application.AutoCorrect.AutoFillFormulasInLists = False

    Target.Offset(0, PriceDiscountOffset).Formula = "=IF([@[Price]]<>"""", -([@[Price]]-[@[Pricelist]])/[@[Price]],"""")"
    Application.EnableEvents = True
    End If

    If Not Intersect(Target, oListObj.ListColumns("Discount").DataBodyRange) Is Nothing Then
    Application.EnableEvents = False


    Application.AutoCorrect.AutoFillFormulasInLists = False
    Target.Offset(0, -PriceDiscountOffset).Formula = "=[@[Pricelist]]-([@[Pricelist]]*[@[Discount]])"
    Application.EnableEvents = True
    End If


End Sub

0 个答案:

没有答案