• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Autofill selection for a dynamic range

AMC

New Member
Hello awesome VBA gurus,

I'm working on a VBA script for processing some data from a couple of workbooks and creating a pivot chart. I am mostly done but have an issue that I'm hoping someone here can help me with.
Columns A & B will contain start/end dates and times which get pulled from a database query. The number of date/time values in these columns will vary with each query.
I want to find out if there is a way to change the range selections that I have below from fixed to dynamic. In the example code below Column C has cells with data down to C308 and I'm manually selecting the range to auto fill the data in the range A301:B308 based on what I have in A301:B301. Is there a way that I can use the last cell in colum C as a reference to determine my lastrow and then fill column A and B up until the first empty cell in A & B?


Code:
' Copy down DT_TM values and format
  Range("A2000").End(xlUp).Offset(1, 0).Select
  Range("A301:B301").Select
  Selection.AutoFill Destination:=Range("A301:B308"), Type:=xlFillDefault
  Range("A301:B308").Select
  Range("A1:B1").Select
  Range(Selection, Selection.End(xlDown)).Select
  Selection.NumberFormat = "m/d/yy h:mm;@"

I have used the following function to autofill cells in another column but not sure how to implement this in the case above.

Code:
lastrow = Range("I2000").Endxlup.Row
Selection.AutoFill Destination:=Range("J2:J" & lastrow), Type:=xlFillDefault


Thank you.
 
Once you have the variable with the row number, you can concatenate it into the address. Here's your revised code (I also took out all the extra selecting that was going on)
Code:
Sub FillData()
Dim lastRow As Long

Application.ScreenUpdating = False
lastRow = Cells(Rows.Count, "C").End(xlUp).Row
Range("A301:B301").AutoFill Destination:=Range("A301:B" & lastRow), Type:=xlFillDefault
Range("A1:B" & lastRow).NumberFormat = "m/d/yy h:mm;@"
Application.ScreenUpdating = True

End Sub
 
  • Like
Reactions: AMC
Thank you Luke!
All I had to do was set the range to start from A2 so that the autofill would work for any length of data in my range.

:awesome:
 
Back
Top