简体   繁体   English

VBA中根据相邻单元格设置默认值

[英]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.需要一个正确的代码而不是任何“IF”公式。 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.当我在 C8:C17 范围内的任何单元格中写入内容时,默认值 1 应等于 F8:F17 范围内的同一单元格。 Which can be changed.哪个可以改变。 And when C8:C17 is empty then F8:F17 should also be empty.当 C8:C17 为空时,F8:F17 也应该为空。

Please don't do the constant Select and ActiveCell : you might replace:请不要执行常量SelectActiveCell :您可能会替换:

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:而且,您可以执行以下操作,而不是使用RC

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

In top of this, you can use the whole range of F8:F17 :最重要的是,您可以使用F8:F17的整个范围:

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

This is already a big decrease of obsolete code.这已经是过时代码的大幅减少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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