Excel范围少笨拙

时间:2018-12-08 14:54:32

标签: excel vba

作为一个老狗(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

2 个答案:

答案 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,以确保声明了所有变量。 (也许您已经有了这个,我不知道。您的代码开头似乎丢失了。)
  • 限定工作簿(例如ThisworkbookSet对其的引用),否则将假定它是代码执行时处于活动状态的任何一个。
  • 我的理解是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