VBA changes complex formula

一笑奈何 提交于 2019-12-23 19:15:50

问题


I use code with Radio Button (see last code) to insert a new row into row 15, which pushes the old data down, and at the same time, copies the same formulas into row 15 that were once there (in row 15) before the button is clicked.

Once the button is clicked, I can enter 3 digit data into E15, then hit enter, and all formulas calculate across row15, based on what is entered in E15.

Now I love how the code performs, but for some reason, the formula in CG15 changes from

=IF(CF15=1,IF(CF15<>"",COUNTBLANK(INDEX(CF14:CF$14,MATCH(9.99999999999999E+307,CF14:CF$14)):CF15),""),"")

to

=IF(CF15=1,IF(CF15<>"",COUNTBLANK(INDEX(CF13:CF$14,MATCH(9.99999999999999E+307,CF13:CF$14)):CF15),""),"")

I can't figure out if the issue is in the code or formula in CG15 Here's a "test" file and below is the code

test sheet

Sub AddNewDrawing()
'
' AddNewDrawing Macro
'

'
    Rows("15:15").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("A16:ua16").Select
    Selection.AutoFill Destination:=Range("A15:ua16"), Type:=xlFillDefault
    Range("A15:ua16").Select
    Range("E15").Select
    Selection.ClearContents
End Sub

This might be simple fix but I am stumped. I need the formula to remain the same and not change.

Here is more in depth information as to what each code does. Column CF15 has this formula which returns 1 if the condition is met.

=IF(COUNTIF($AW16:$CC18,O15),1,IF(COUNTIF($AW16:$CC18,P15),1,IF(COUNTIF($AW16:$CC18,Q15),1,"")))

Column CG15 has this formula which counts skips(blank cells) between each of the 1's in column CF15. Note: CG$14 has a permanent 0(zero) which acts as a place holder for the beginning of the count.

=IF(CF15=1,IF(CF15<>"",COUNTBLANK(INDEX(CF14:CF$14,MATCH(9.99999999999999E+307,CF14:CF$14)):CF15),""),"")

Thank you


回答1:


When you insert a new row 15, the formula in CG15 is pushed down to CG16 and the relative addresses in the formula that refer to row 15 (e.g. CF15) become row 16 (e.g. CF16).

However, the relative addresses that are less than 15 like CF14 are unaffected by the row insertion. When you 'backfill' the formula from CG16 to CG15 they are all affected so CF14:CF$14 becomes CF13:CF$14 just as CF16 reverts back to the original CF15.

Change the formula to something that isn't affected by the relative difference between row insertion or backfill.

A row relative CF14 can be written in CG15 as,

index(CF:CF, row()-1)

So that makes your formula,

=IF(CF15=1, COUNTBLANK(INDEX(CF$14:index(CF:CF, row()-1), MATCH(1e99, CF$14:index(CF:CF, row()-1))):CF15), text(,))


来源:https://stackoverflow.com/questions/50659580/vba-changes-complex-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!