我想在公式中使用用户输入,如下所示:
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
有关。
如何安排代码以便我可以使用呢?
答案 0 :(得分: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
答案 1 :(得分:0)
我认为这应该有用
范围(“AG2”)。FormulaR1C1 =“= ROUNDUP(RC [-6] * " & StockDays & "
/ 90,0)”
你犯的错误是,你在哪里应用公式但是忘了用变量中的值替换你使用的变量