dynamic公式自动填充

我想知道如何将此代码转换为列I的dynamic范围自动填充,以便以后可以自由编辑Excel表而不需要调整vba代码。

Sub Rowcount() 'Charles, M Dim H As Long Set sh = Worksheets("Report-Charles, M") H = sh.UsedRange.Rows.Count Range("I2:I" & H).Formula = "=IF((AND(OR(E2=""Unrated"",E2=""""),OR(G2<>""Unrated"",G2<>""""))),G2,IF(E2>=""4,25"",""High Performance"",IF(E2<""3,35"",""Low Performance"",IF(AND(E2>=""3,35"",E2<""4,25""),""Medium Performance"",""Unrated""))))" MsgBox (H) & "Rows have been Autofilled with 3 scale Rating Results" End Sub 

看看自动填充function:

 Range("I2:I" & H).AutoFill Destination:=Range("I2:I2000"), Type:=xlFillDefault 

首先,您只隐式引用Report-Charles,M作为将.Formula放入的ActiveSheet属性 ; 没有明确的直接引用。

其次,要指定公式,请使用直接.Formula写入, Range.AutoFill方法或Range.FillDown方法 。

最后,通过VBA编写一个公式.Formula应该用EN-US语法和区域设置来完成。 如果要使用非EN-US区域设置(如3,354,25使用Range.FormulaLocal属性 。

高于一切,把数字视为数字; 而不是像文字那样的数字。

 with Worksheets("Report-Charles, M") h = .UsedRange.Rows.Count .Range("I2:I" & H).FormulaLocal = _ "=IF((AND(OR(E2=""Unrated"", E2=TEXT(,)), OR(G2<>""Unrated"", G2<>TEXT(,)))), G2, IF(E2>=4,25, ""High Performance"", IF(E2<3,35, ""Low Performance"", ""Medium Performance"")))" .Range("I2:I" & H).Formula = _ "=IF((AND(OR(E2=""Unrated"", E2=TEXT(,)), OR(G2<>""Unrated"", G2<>TEXT(,)))), G2, IF(E2>=4.25, ""High Performance"", IF(E2<3.35, ""Low Performance"", ""Medium Performance"")))" end with with Worksheets("Report-Charles, M") 'any of the following will fill column I with formulas to the last row in .UsedRange 'all of the following assumes a valid formula in I2 h = .UsedRange.Rows.Count .Range("I2:I" & H).Formula = .Range("I2").Formula .Range("I2:I" & H).FillDown .Range("I2:I" & H).DataSeries Rowcol:=xlColumns, Type:=xlAutoFill .Range("I2").AutoFill Destination:=.Range("I2:I" & H), Type:=xlFillDefault end with 

我已经缩短了一个IF条件,因为AND是不必要的,而Medium是默认的响应。 使用TEXT(,)""是一样的,不需要加双引号。