简体   繁体   中英

Autofill a table with a dynamic range in Excel VBA

I'm trying to autofill a table with a variable range based on date (eg Date range of 6/10/2018 - 6/13/2018 it autofills from the last row which is 6/10/2018 to 6/13/2018).

Here is my code so far where at the auto fill step it kicks a mis-match error:

Set Table = Adspend.Worksheets("Summary").ListObjects("Spend")
Set TableCell = Table.Range.Cells(2, Table.ListColumns(1).Index)

LastRow = Table.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

If IsEmpty(Table.Range.Cells(2, Table.ListColumns(1).Index)) = True Then
Table.Range.Cells(2, Table.ListColumns(1).Index) = 
Adspend.Worksheets("Summary").Range("B1").Value
End If


If TableCell.Value < Adspend.Worksheets("Summary").Range("C1").Value Then
        DatePeriod = Adspend.Worksheets("Summary").Range("C1").Value - 
TableCell.Value

        NewDate = LastRow + DatePeriod



        Table.Range.Cells(2, Table.ListColumns(1).Index).AutoFill Destination:=Table.Range(Cells(LastRow, Table.ListColumns(1)), Cells(NewDate, Table.ListColumns(1)))




End If

If the first column of your Spend table is in column O and there is nothing beneath it, switch the autofill to a data series using the last date value in column O and an integer in C1 as the stop.

Option Explicit

Sub Macro1()
    Dim datePeriod As Long

    With Worksheets("Summary")
        datePeriod = .Range("C1").Value

        With .Cells(.Rows.Count, .ListObjects("Spend").Range.Column).End(xlUp)
            .DataSeries Rowcol:=xlColumns, Type:=xlChronological, _
                        Date:=xlDay, Step:=1, Stop:=.Value + datePeriod
        End With
    End With
End Sub

If you want to convert that to ListObject syntax, it shouldn't be hard but a DataSeries with a stop should be easier than an autofill into a destination range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM