为Sub VBA Excel提供dynamic范围的值

我想通过行列值到将调用一个函数来计算一些逻辑的子。

在编写一个子程序之前,我只是定义了一个函数,并手动将值传递给函数,并拖动到我需要的列。

但是现在我想创build一个能自动将公式应用到列的范围的东西。

这是我想要做的代码,也许它不是最好的方式,但build议。

Function addDiscount(Qty, Price) ' ' addDiscount Macro ' adds Discount to given price and quantity ' ' Keyboard Shortcut: Ctrl+h If (Qty >= 10 Or Price >= 200) Then addDiscount = 30 * 0.01 Else addDiscount = 0 End If addDiscount = Application.Round(addDiscount, 2) End Function Sub insertAddDiscount() Sheets("Sheet1").Select Range("F9:F30").Select Dim i As Integer For i = 9 To 30 Selection.Formula = "=addDIscount($G$i,$E$i)" Selection.Columns.AutoFit Next i End Sub 

由于您在公式中使用variablesi ,因此您需要将其放在"之外。

replace你的线路:

 Selection.Formula = "=addDIscount($G$i,$E$i)" 

有:

 Selection.Formula = "=addDIscount($G" & i & ",$E" & i & ")" 

不过 ,让我build议一个解决scheme,不需要依赖Select范围,以后再使用Selection ,而是依赖完全限定的Range对象(这也会缩短代码的运行时间)。

 Sub insertAddDiscount() Dim i As Long With Sheets("Sheet1") For i = 9 To 30 .Range("F" & i).Formula = "=addDIscount($G" & i & ",$E" & i & ")" Next i .Range("F9:F30").Columns.AutoFit End With End Sub