Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel Range less clumsy

Tags:

excel

vba

As an old dog (age 73) learning new (Excel VBA) tricks, I am reasonably happy with putting together the code below. But I think it could be cleaner. How would you have coded it?

Dim thisDate As Double  'start timestamp
thisDate = Now()
With Sheets("Pressure Log")
    lastRow = .Range("B" & .Rows.Count).End(xlUp).Row     'populate next row with date/time
    .Range("B" & lastRow + 1 & ":G" & lastRow + 1).Borders.LineStyle = xlContinuous
    .Range("B" & lastRow).Offset(1) = Format(thisDate, "dddd")
    .Range("B" & lastRow).Offset(1, 1) = Format(thisDate, "mm/dd/yyyy")
    .Range("B" & lastRow).Offset(1, 2) = Format(thisDate, "hh:mm AM/PM")
    .Range("B" & lastRow).Offset(1, 3).Select 'position for data    
End With
End Sub
like image 843
grNadpa Avatar asked Feb 25 '26 17:02

grNadpa


1 Answers

I think questions of this nature are meant for CodeReview. You may get a better response there.

I'm not sure my version is necessarily better:

Option Explicit

Private Sub AddCurrentDateTimeAfterLastRow()
    Dim thisDate As Double
    thisDate = Now()

    With ThisWorkbook.Worksheets("Pressure Log")
        Dim lastRow As Long
        lastRow = .Range("B" & .Rows.Count).End(xlUp).Row

        Dim outputArray() As Variant
        ReDim outputArray(1 To 3)

        outputArray(1) = Format(thisDate, "dddd")
        outputArray(2) = Format(thisDate, "mm/dd/yyyy")
        outputArray(3) = Format(thisDate, "hh:mm AM/PM")

        With .Cells(lastRow + 1, "B").Resize(1, UBound(outputArray))
            .Borders.LineStyle = xlContinuous
            .FormulaLocal = outputArray
            .Parent.Parent.Activate
            .Parent.Activate
            .Cells(1, 3).Select
        End With
    End With
End Sub
  • Put Option Explicit before your code to ensure all variables are declared. (Maybe you already had this, I don't know. The beginning of your code seems to be missing.)
  • Qualify the workbook (e.g. Thisworkbook or Set a reference to it), otherwise it will be assumed to be whichever one is active at the time of code execution.
  • My understanding is Sheets can refer to regular worksheets and chart sheets, whereas Worksheets can only refer to worksheets. So it might be good to be explicit and just use Worksheets.
  • Since you want the macro (at the end) to select the cell, it's important that the worksheet and the workbook (which contain the cell) are active at the time of selection. Otherwise, you risk getting an error.
  • I put your day, date, time into an array, then wrote said array to the worksheet. I just thought the array element assignments were shorter and cleaner (to read and maintain).
like image 186
chillin Avatar answered Feb 27 '26 08:02

chillin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!