作为一个老狗(73岁)学习新的(Excel VBA)技巧,我很乐意将以下代码组合在一起。但我认为它可能更清洁。您将如何编码?
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
答案 0 :(得分:1)
我认为这种性质的问题适用于CodeReview。您在那里可能会得到更好的答复。
我不确定我的版本是否一定会更好:
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
Option Explicit
,以确保声明了所有变量。 (也许您已经有了这个,我不知道。您的代码开头似乎丢失了。)Thisworkbook
或Set
对其的引用),否则将假定它是代码执行时处于活动状态的任何一个。Sheets
可以引用常规工作表和图表表,而Worksheets
仅可以引用工作表。因此,明确明确并仅使用Worksheets
可能会很好。答案 1 :(得分:0)
Option Explicit
Private Const SHEET_NAME As String = "Pressure Log"
' Or change sheet name in Properties window from Sheet1 to wksPressureLog,
' otherwise any sheet renaming will result in code crash
'
' Another optimization - is to assign column positions to constants
' for example column B here is used 3 times, if you'll decide to modify
' table - you'll have to find and change all these 3 instances, and in big
' scripts it will be hard enough to understand what each number means
' Execute only once
Sub FormatColumns()
With Sheets(SHEET_NAME)
.Cells(1, 2).EntireColumn.NumberFormat = "dddd"
.Cells(1, 3).EntireColumn.NumberFormat = "mm/dd/yyyy"
.Cells(1, 4).EntireColumn.NumberFormat = "hh:mm AM/PM"
End With
End Sub
Sub InsertData()
With Sheets(SHEET_NAME)
With .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row + 1, 2)
.Resize(1, 5).Borders.LineStyle = xlContinuous
.Resize(1, 3) = Now()
.Offset(0, 3).Select 'position for data
End With
End With
End Sub