0

我想在公式中使用用户输入,如下所示:

Sub example()

Dim StockDays As Integer
StockDays = InputBox(Prompt:="How many days?")

Range("AG2").FormulaR1C1 = "=ROUNDUP(RC[-6]*" & StockDays & "/90, 0)"
Range("AG2").Select
Selection.AutoFill Destination:=Range(Cells(2, 33), Cells(1500, 33))

End Sub

运行时,上面的代码在 ROUNDUP 行抛出错误。

运行时错误 1004。
应用程序定义或对象定义的错误。

我认为问题与变量有关StockDays

我该如何安排代码以使其工作?

4

2 回答 2

3

我已经评论了代码,所以你理解它应该没有任何问题:)

Option Explicit

Sub example()
    Dim StockDays As Integer

    '~~> Type:=1  will ensure that the user enters only numbers
    StockDays = Application.InputBox(Prompt:="How many days?", Type:=1)

    '~~> No Need to autofill. You can fill all the range in one go
    Thisworkbook.Sheets("Sheet1").Range("AG2:AG1500").FormulaR1C1 = _
    "=ROUNDUP(RC[-6] * " & StockDays & "/ 90, 0)"

    'OR this as mentioned in your comment

    Thisworkbook.Sheets("Sheet1").Range("AG2:AG1500").FormulaR1C1 = _
    "=ROUNDUP((RC[-6]* " & StockDays & "/90),0)"
End Sub
于 2012-12-26T09:17:43.413 回答
0

我认为这应该有效

Range("AG2").FormulaR1C1 = "=ROUNDUP(RC[-6] * " & StockDays & "/ 90, 0)"

您犯的错误是,您在应用公式但忘记将您使用的变量替换为变量中的值

于 2012-12-26T09:14:18.997 回答