vba 您可以在自动填充功能中使用单元格而不是范围吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17306094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:52:27  来源:igfitidea点击:

Can you use Cells instead of Range inside of an Autofill function?

vbaexcel-vbaexcel-2010excel-2013excel

提问by TheTreeMan

If I have this, for example:

如果我有这个,例如:

Sub ExampleThing()

    Counter = 13
    For i = 1 To Counter
        Range("A" & i) = Rnd
    Next

    Range("B1").Formula = "=(PI()*A1)"
    Range("B1").Select
    Selection.AutoFill Destination:=Range("B1:B" & Counter), Type:=xlFillDefault

End Sub

What if, instead of using Range() under Destination, I wanted to use Cells()? Like, instead of having cell references inside the range function, replace that with Cells(), like this:

如果我想使用 Cells() 而不是在 Destination 下使用 Range() 怎么办?就像,而不是在 range 函数内有单元格引用,用 Cells() 替换它,像这样:

Selection.AutoFill Destination:=Range("Cells(1,2):Cells(Counter,2)"), Type:=xlFillDefault

I've been playing around with it, and can't seem to get it to work.

我一直在玩它,似乎无法让它工作。

回答by Doug Glancy

You're very close. Here's a version with your variables declared (which you really should do) and the Selectstatements eliminated (also a good practice):

你很亲近。这是一个声明了变量的版本(您确实应该这样做)并且Select删除了语句(也是一个很好的做法):

Sub ExampleThing()
Dim Counter As Long
Dim i As Long

Counter = 13
For i = 1 To Counter
    Range("A" & i) = Rnd
Next
Range("B1").Formula = "=(PI()*A1)"
Range("B1").AutoFill Destination:=Range(Cells(1, 2), Cells(Counter, 2)), Type:=xlFillDefault
End Sub