简体   繁体   中英

Setting the default value based on the adjacent cell in VBA

Sub Print_New()
'
' Print_New Macro
'

'
    ActiveSheet.Unprotect
    ActiveSheet.Range("$B$7:$G$24").AutoFilter Field:=1, Criteria1:="<>"
    ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
        IgnorePrintAreas:=False
    ActiveSheet.Range("$B$7:$G$24").AutoFilter Field:=1
    ActiveSheet.Protect
    Sheets("Bill (1)").Copy Before:=Sheets(5)
    ActiveSheet.Unprotect

    Range("C8:C17,D20,E20:F20").Select
    Range("E20").Activate
    Selection.ClearContents
    Range("G20").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-2]="""","""",5%)"
    Range("F8").Select
    Range("F8").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F9").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F10").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F11").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F12").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F13").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F14").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F15").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F16").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("F17").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")"
    Range("C8").Select
    ActiveSheet.Protect
    ActiveWorkbook.Save
End Sub

Need a proper code instead of any "IF" formula. When I write something in any cell in the range C8:C17, the default value 1 should be equal to the same cell in the range F8:F17. Which can be changed. And when C8:C17 is empty then F8:F17 should also be empty.

Please don't do the constant Select and ActiveCell : you might replace:

Range("G20").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-2]="""","""",5%)"

by:

Range("G20").FormulaR1C1 = "=IF(RC[-2]="""","""",5%)"

And, instead of using RC , you might do the following:

Range("G20").Formula = "=IF(Offset(-2;0)="""","""",5%)"

In top of this, you can use the whole range of F8:F17 :

Range("F8:F17").Formula = "IF(Offset(-3;0)>0,1,"""")"

This is already a big decrease of obsolete code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM