Autofill with a dynamic range

落爺英雄遲暮 提交于 2019-12-08 01:06:34

问题


I'm not a very experienced VBA programmer, I know the very basics. Right now I'm constructing a program to automate some work, using record and then cleaning. It has worked well up until a calculation that takes too long for me. Its a simple nested IF statement

ActiveCell.FormulaR1C1 = _ "=IF(RC[-16]="""",""MISSING"",IF(RC[-14]="""",""MISSING"",RC[-14]-RC[-16]))"

We deal with data that can range from being only 10 rows up to a couple hundred thousand. My "solution" that I'm not happy with so far has limited the autofill to range A1:A35000 - which still takes excel a bit to process. This was the solution to avoid xldown taking me to the 1 millionth row. Further, I've tried reducing sheet size, that works as well but is not a good solution.

This is what the code looks like Selection.AutoFill Destination:=ActiveCell.Range("A1:A35000"), Type:= _ xlFillDefault

What I want to do is to either A) autofill from a range referenced by a number in a given cell (so if the data i put is 500 rows I have a cell I type in 500 and all the autofills go from A1:A500)

B) more preferably, this would be done automatically by having the program already recognize the range to autofill.

I've checked through the solutions and can't figure out how to apply it to my situation.

Thank you for any help/support you can offer.


回答1:


I think you may be looking for the following ...

Dim ws as Worksheet
Set ws = Worksheets("Sheet1")

Dim usedRows as Long

'Option One (not recommended): USED RANGE METHOD 
usedRows = ws.UsedRange.Rows.Count

'Option Two (more robust) .END(xlUp) METHOD (Assuming you have your Data in column "RC")
usedRows = ws.Cells(ws.Rows.Count, "RC").End(xlUp).Row

'YOUR
'CODE
'HERE

Selection.AutoFill Destination:=ws.Range(Cells(1,1),Cells(usedRows,1)), Type:= _ xlFillDefault

if that column has the most used rows of any in your worksheet.

Thanks to @scott for pointing out the .End(xlUp) option's superiority :)



来源:https://stackoverflow.com/questions/14161637/autofill-with-a-dynamic-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!