Search code examples
vbaexcelexcel-2010excel-tables

Filling date on specific range inside a table


I have a table where i would like to insert a date as shown in image. It will copy the date to some continuos range. The program must find the range and then insert date using inputbox. I used the code below. The problem is it is not selecting the range inside a table. How to solve this. Help me

enter image description here

Sub FillFirstDay()
Dim ws As Worksheet
Dim rng As Range
Dim LastRow As Long
Dim table As ListObject
Dim dat As Date

Set ws = Sheets("Raw Data")
dat = Application.InputBox(prompt:="Enter the received date of the current Month", Title:="Date", Default:=Format(Date, "dd/mm/yyyy"), Type:=2)

If dat = False Then
MsgBox "Enter a Date", , "Date"
Exit Sub
End If

With ws
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    firstRow = .Range("C" & .Rows.Count).End(xlUp).Row + 1
    Set rng = Range(.Range("C" & firstRow), .Range("C" & LastRow))
End With

If firstRow >= LastRow Then Exit Sub

With rng
    .Value = dat
    .NumberFormat = "m/d/yyyy"
    .NumberFormat = "[$-409]dd-mmm-yy;@"
End With
End Sub

Solution

  • This line here is the problem:

    firstRow = .Range("C" & .Rows.Count).End(xlUp).Row + 1
    

    The .End(xlUp) code catches the bottom of the table on its way up. You have to do it twice to move up to the bottom of where the data is. This modified line will fix your issue:

    firstrow = .Range("C" & .Rows.Count).End(xlUp).End(xlUp).Row + 1