生成时间间隔
- 调整第一个主程序
generateTimeIntervals 中的常量以满足您的需要,然后运行它。
- 第二个过程
getTimeIntervals 正在被主过程调用。
- 此外,您还可以使用
getTimeIntervals Data, StartTime, EndTime, MinutesInterval。在这 4 个参数之后,还有 3 个参数被省略(根据您帖子中的设置进行调整,例如,如果您将 include2ndColumn 设置为 True,您将获得两列:From 和 To。其余两个参数非常不言自明。
守则
Option Explicit
Sub generateTimeIntervals()
Const wsName As String = "Sheet1"
Const StartLocation As String = "B1"
Const EndLocation As String = "B2"
Const ResultLocation As String = "B3"
Const MinutesInterval As Long = 30
Const NumFormat As String = "MM/DD/YYYY HH:MM"
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Worksheets(wsName)
Dim StartTime As Date
StartTime = ws.Range(StartLocation)
Dim EndTime As Date
EndTime = ws.Range(EndLocation)
' Generate time intervals to Result Array.
Dim Data As Variant
getTimeIntervals Data, StartTime, EndTime, MinutesInterval
If IsEmpty(Data) Then
GoTo NoData
End If
' Write values from Result Array to Result Range.
With ws.Range(ResultLocation)
' Clear Result Range Column(s) starting from Result Location.
.Resize(ws.Rows.Count - ws.Range(ResultLocation).Row + 1, _
UBound(Data, 2)).Clear
' Apply formatting to Result Range.
.Resize(UBound(Data, 1), UBound(Data, 2)).NumberFormat = NumFormat
' Write values from Result Array to Result Range.
.Resize(UBound(Data, 1), UBound(Data, 2)).Value = Data
End With
' Inform user.
MsgBox "Generated " & UBound(Data, 1) & " time intervals.", _
vbInformation, "Success"
ProcExit:
Exit Sub
NoData:
MsgBox "Unable to generate.", vbExclamation, "No Data"
GoTo ProcExit
End Sub
Sub getTimeIntervals(ByRef Data As Variant, _
ByVal StartTime As Date, _
ByVal EndTime As Date, _
MinutesInterval As Long, _
Optional include2ndColumn As Boolean = False, _
Optional includeLast As Boolean = False, _
Optional excludeFirst As Boolean = False)
Data = Empty
If EndTime <= StartTime Then
GoTo ProcExit
End If
Dim Interval As Double
Interval = MinutesInterval / 24 / 60
Dim addLast As Long
If includeLast Then
addLast = 1
End If
Dim removeFirst As Long
If excludeFirst Then
removeFirst = 1
End If
Dim DataCount As Long
DataCount = (EndTime - StartTime) / Interval + addLast - removeFirst
If DataCount < 1 Then
GoTo ProcExit
End If
Dim CurrentTime As Date
CurrentTime = StartTime + removeFirst * Interval
Dim i As Long
If include2ndColumn Then
ReDim Data(1 To DataCount, 1 To 1)
For i = 1 To UBound(Data, 1)
Data(i, 1) = CurrentTime
CurrentTime = CurrentTime + Interval
Next i
Else
ReDim Data(1 To DataCount, 1 To 2)
For i = 1 To UBound(Data, 1)
Data(i, 1) = CurrentTime
CurrentTime = CurrentTime + Interval
Data(i, 2) = CurrentTime
Next i
End If
ProcExit:
End Sub